3

Why implicit conversion from const char* to std::string does not work in the latter case? Link a reference to C++ standard if possible, please.

Variant 1:

struct Foo {
    Foo(const char* a) {}
};

int main() {
   // works well for a "const char*" accepting constructor
   Foo* foo = new Foo[1] { "a" };
}

Variant 2:

struct Foo {
    Foo(std::string a) {}
};

int main() {
   // could not convert from "const char*" to "Foo"
   Foo* foo = new Foo[1] { "a" };
}
2
  • There's no such thing as an implicit cast. There is a cast (explicit type conversion) and type coalescing (implicit type conversion), decide which one. Commented Apr 12, 2013 at 10:21
  • check how's the page named: en.cppreference.com/w/cpp/language/implicit_cast Commented Feb 19, 2014 at 5:53

1 Answer 1

6

At most one user-defined conversion is allowed in a user-defined conversion sequence (12.3p4).

You can use an extra level of braces to make it work:

   Foo* foo = new Foo[1] { {"a"} };

Note that because of a bug in clang it requires Foo to have a default constructor Foo::Foo() even though it will not actually be called.

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm... Looks good, works well with g++, but not with clang(LWS example)
@balki clang is broken; there's a simple workaround (add a default constructor). Reporting the bug now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.