Search code examples
c++c++11templatesstandards-compliancetemplate-argument-deduction

Default vs Deduced template parameter?


In the following :

template<typename Type>
struct MyClass
{
    template<typename OtherType> MyClass(const MyClass<OtherType>& x);
    template<typename OtherType = Type> void test(const MyClass<OtherType>& x);
};

In the function test what is done between :

Case 1 : The default parameter is priority : the conversion constructor MyClass<Type>(const MyClass<OtherType>& x) is implicitely called and MyClass<Type>::test<Type>(const MyClass<Type>& x) is called.

Case 2 : The deduced parameter is priority : MyClass<Type>::test<Type>(const MyClass<OtherType>& x) is called.


I think that the good answer is the second one, but I'm not sure. Can you confirm me that (and that this situation is well-defined by the standard) ?


EDIT : The test function is called by :

MyClass<double> d;
MyClass<unsigned int> ui;
d.test(ui); // <- So the question is : is ui implicitely 
            //    converted to MyClass<double> or not ?

Solution

  • test will be called as

    MyClass<double>::test(const MyClass<unsigned int> &)
    

    i.e. there will be no conversion of ui from MyClass<unsigned int> to MyClass<double>.

    A default template argument never overrides a given one. It is only used when no template argument is given and the compiler can't deduce it from the function arguments.

    From the C++11 Standard:

    (§14.8.2/5) The resulting substituted and adjusted function type is used as the type of the function template for template argument deduction. If a template argument has not been deduced, its default template argument, if any, is used. [ Example:

    template <class T, class U = double>
    void f(T t = 0, U u = 0);
    void g() {
      f(1, ’c’);      // f<int,char>(1,’c’)
      f(1);           // f<int,double>(1,0)
      f();            // error: T cannot be deduced
      f<int>();       // f<int,double>(0,0)
      f<int,char>();  // f<int,char>(0,0)
    }
    

    — end example ]