6

Given the following code, why doesn't the compiler resolve the implicit conversion when constructing Bar? That is, construct Foo just like a was constructed which is (should) then be used to construct 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?");
}
1
  • It's part of the standard, implicit conversions can't be chained like that. You can only have one implicit conversion. Commented Aug 12, 2013 at 15:23

2 Answers 2

9

You are not allowed more than one user defined implicit conversion. The Foo example involves one, the Bar example involves two.

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

Comments

4

The compiler is only allowed to make a single 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

Constructing Bar that way would require two.

4 Comments

Your opening sentence is not correct. The compiler is allowed to make a single implicit user-defined conversion. It can perform as many implicit standard conversion as it likes
I wish it liked none.
@ArmenTsirunyan thanks for pointing out this critical oversight. Answer updated.
@ArmenTsirunyan, en.cppreference.com/w/cpp/language/implicit_cast states that only up to two standard conversions can be performed

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.