I have a couple of questions related to overload resolution in C++. Consider this example:
extern "C" int printf (const char*, ...);
struct X {};
template <typename T>
struct A
{
A() = default;
template <typename U>
A(A<U>&&)
{printf("%s \n", __PRETTY_FUNCTION__);}
};
template <typename T>
struct B : A<T>
{
B() = default;
template <typename U>
operator A<U>()
{printf("%s \n", __PRETTY_FUNCTION__); return {};}
};
int main ()
{
A<X> a1 (B<int>{});
}
If I compile it with g++ -std=c++11 a.cpp
, the A
's constructor will get called:
A<T>::A(A<U>&&) [with U = int; T = X]
If I compile program with g++ -std=c++17 a.cpp
, it will produce
B<T>::operator A<U>() [with U = X; T = int]
If I comment A(A<U>&&)
out and once again compile it with g++ -std=c++11 a.cpp
, the conversion operator will be called:
B<T>::operator A<U>() [with U = X; T = int]
- Why is the conversion operator even considered in the third case? Why is the program not ill-formed? [dcl.init] states:
Otherwise, if the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (16.3.1.3), and the best one is chosen through overload resolution (16.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.
- Why
A
's constructor is the better choice in the first case?B
's conversion operator seems to be the better match since it doesn't require an implicit conversion fromB<int>
toA<int>
. - Why the first and second cases yield different results? What has changed in C++17?
P.S. Does anyone know where I can find a detailed guide that describes how conversion operators participate in overload resolution, i.e., the ways they interact with the constructors when different types of initialization take place. I know that the standard provides the most accurate description, but it seems that my interpretation of the standard wording has little in common with its correct meaning. Some kind of rule of thumb and additional examples might be helpful.