c++c++17ctaddeduction-guide

Can a class template have more than one user defined deduction guide for the same constructor?


Is it valid to have more than one user defined deduction guide for the same constructor in a class template?

For example:

template<typename T>
class A {
    T t;
public:
    A(T t): t(std::move(t)) { /* ... */ }
};

template<typename T>
  requires ( std::floating_point<std::remove_cvref_t<T>> ||
             std::integral<std::remove_cvref_t<T>> ) 
A(T&& a) -> A<double>;

A(const char* s) -> A<std::string>;

If it is, how does the compiler picks which one to use in case more than one can fit?


Solution

  • Is it valid to have more than one user defined deduction guide for the same constructor in a class template?

    Deduction guides are not associated with particular constructors; as such, the question does not really make sense. A deduction guide only tells the compiler how to pick one particular specialization of the class template based on the arguments supplied. In the above example, when the argument has type const char*, the second deduction guide tells the compiler to pick the type A<std::string>.

    To be precise, the entire list of deduction guides, including both ones explicitly declared by the programmer and ones implicitly generated from the class definition, is subject to overload resolution and the best one is chosen based on the arguments provided. This determines the concrete type that will be constructed, such as A<std::string>.

    Once the concrete class type, such as A<std::string>, has been determined, the deduction guides have done their job. A second overload resolution is then performed using all the constructors of that class type and the arguments supplied. That process picks a single best constructor, which is then used to initialize the object.