1
#include <typeinfo>
#include <iostream>
using namespace std;

template<typename T, typename U = T> void f1(T a, U b)
{
  cout<<typeid(a).name()<<endl;
  cout<<typeid(b).name()<<endl;
}

int main()
{
  f1<float>(1,2);
}

output:

f

i ----> why is it int not default float as per template instantiation?

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68
  • 5
    Because deduction takes priority over default. – Patrick Roberts Apr 10 '21 at 14:53
  • And why is it so? Any duplicate questions to refer? – Sreeraj Chundayil Apr 10 '21 at 14:57
  • 1
    Not necessarily a duplicate, but [here's a similar one](https://stackoverflow.com/q/66945729/1541563). Someone more familiar with this tag than me might be able to find a better duplicate. – Patrick Roberts Apr 10 '21 at 14:58
  • 1
    A "default" is the last resource; used when nothing else is used. Default template types/values are used when (1) the call doesn't explicit the type/value (as you do with `` for the first type) and (2) the type isn't deduced from the argument. – max66 Apr 10 '21 at 15:06
  • Why is it so? Because the function argument can always initialize a `U` if its deduced from it. If the `U` is taken from the default argument first as a you think it should, there is no such guarantee anymore. – StoryTeller - Unslander Monica Apr 10 '21 at 17:09

1 Answers1

1

Default template arguments are last resort, and used only when the argument wasn't specified or deduced.

It's specified in [temp.deduct]/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 and its corresponding template parameter has a default argument, the template argument is determined by substituting the template arguments determined for preceding template parameters into the default argument. If the substitution results in an invalid type, as described above, type deduction fails. [ 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 ]

rustyx
  • 80,671
  • 25
  • 200
  • 267