3

[C++11: 12.3/2]: User-defined conversions are applied only where they are unambiguous. [..]

Yet, the following compiles just fine in GCC and Clang trunk:

struct B;
struct A
{
    A();
    operator B();
};

struct B
{
    B(const A&);
};

int main()
{
    A a;
    (B)a;
}

What am I missing?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

7

The cast notation (B)a is equivalent in this case to static_cast<B>(a) (§5.4/4). This in turn has the same semantics as the initialization B t(a), where t is a temporary (§5.2.9/4). Since B has class type, and the initialization is a direct-initialization, only the constructors of B are considered (§8.5/16). The applicable constructors are:

  • converting constructor B::B(const A&)
  • implicitly defined copy constructor B::B(const B&)
  • implicitly defined move constructor B::B(B&&)

The converting constructor wins overload resolution since the implicit conversion from A to const A& is an exact match.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312