Oliv
Oliv

Reputation: 18041

Why conversion can involve two user defined conversion function/constructor?

I am trying to understand which rules in the standard justify the compiler behavior below. So this question is only intended to get a language-lawyer answer.

Let's consider this two classes:

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

The following code compile:

 B b;
 A a{b};

The variable a is direct initialized by a b. According to [dlc.init]/17.6.3:

Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in [over.match.copy],

I understand that the process of direct initialization will list all user-defined conversion sequence that can perform a conversion from B (the source type) to A, the destination type. [over.match.copy] explain where can be found user defined conversion function.

A user defined conversion sequence can only involve 1 user defined conversion function or constructor. But the only conversion path consist in calling both the conversion constructor A::A(int) and the conversion function B::operator int().

So there are no user defined conversion sequence that allows conversion from B to A.

Why according to the standard the initialization A a{b}; could be well formed?

Upvotes: 1

Views: 94

Answers (1)

user2100815
user2100815

Reputation:

It's well-formed because it uses one conversion to convert from a B to an int. Then the constructor for A is called explicitly, using that int as a parameter.

This would be a case where you have two user-defined conversions:

  void f( A a ) {}
  B b;
  f( b  );      

Upvotes: 2

Related Questions