Reputation: 385108
[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
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:
B::B(const A&)
B::B(const B&)
B::B(B&&)
The converting constructor wins overload resolution since the implicit conversion from A
to const A&
is an exact match.
Upvotes: 7