Home > Software design >  Calling overloading template function by func(1) and func<int>(1) leads to difference result
Calling overloading template function by func(1) and func<int>(1) leads to difference result

Time:01-24

I have two template functions:

template <typename T>   
void func(T a)
{ std::cout << "func(T a)" << std::endl; }


template <typename T>  
void func(int a)
{ std::cout << "func(int a)" << std::endl; }

And calling func which different method will lead to different result:

func(1);       // call func(T a)
func<int>(1);  // call func(int a)

Here is the demo. I originally thought that func(1) and func<int>(1) are identical, but it seems that I was wrong. Does compiler treat func(1) and func<int>(1) differently? Thanks for any help!

CodePudding user response:

The call func<int>(1); chooses the second overload because it is more specialized.

The call func(1); can't choose the second overload, because the second overload has a template parameter T which is neither given a template argument explicitly (as in func<int>(1);), nor can be deduced from the function parameter/argument pair (as T in the first overload can from the argument 1 to the T a parameter). If a template argument can't be deduced and isn't explicitly given, then the overload is non-viable in overload resolution. The only remaining overload is the first one, which is then chosen.

  • Related