Implicit conversions in C ++

Given the following code, why does the compiler not allow implicit conversion when building Bar ? That is, Foo is constructed, how was a constructed, which (should) be used to build the Bar ?

 #include <string> class ImplicitlyConvertToChar { public: ImplicitlyConvertToChar(const char* a_char) : m_string(a_char) { } ImplicitlyConvertToChar(const char* a_char, size_t a_end) : m_string(a_char) { } template <typename T_String> ImplicitlyConvertToChar(T_String const& a_string) : m_string(a_string.begin()) { } operator char const * () const { return m_string; } const char* m_string; }; class Foo { public: Foo(const ImplicitlyConvertToChar& a_charLike) : m_string(a_charLike) { } const char* m_string; }; class Bar { public: Bar(const Foo& a_foo) : m_foo(a_foo) { } Foo m_foo; }; int main() { Foo a("this works"); Bar b("Why doesn't this?"); } 
+6
source share
2 answers

You are not allowed to use the implicit conversion of more than one user. The Foo example includes one; the Bar example includes two.

+9
source

The compiler is allowed only one implicit user-defined conversion.

See http://en.cppreference.com/w/cpp/language/implicit_cast

 A user-defined conversion consists of: zero or one non-explicit single-argument constructor or non-explicit conversion function calls 

Building a Bar for this will require two.

+4
source

Source: https://habr.com/ru/post/951565/


All Articles