Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

Is this user-defined conversion not ambiguous? If so, what rule allows it?

[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?

Upvotes: 3

Views: 93

Answers (1)

Brian Bi
Brian Bi

Reputation: 119069

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.

Upvotes: 7

Related Questions