Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template function selection [duplicate]

Tags:

c++

templates

template<typename TA, typename TB>
void foo (TA a, TB b); // #1

template<typename T>
void foo (T a, T b); // #2

int a, b;    
foo(a, b);

In this case, foo #2 is called. Why?

like image 378
timmah2014 Avatar asked Nov 10 '22 08:11

timmah2014


1 Answers

If you were to make explicit the template parameters, you would use:

foo<int, int>(a, b);

to call the first function.

You would use:

foo<int>(a, b);

to call the second function.

Since you let the compiler choose the function, it chose the more restrictive function, which is the second one.

Why is the second one more restrictive? The compiler has to deduce one type to use the second function. It has to deduce two types to use the first one.

like image 150
R Sahu Avatar answered Nov 15 '22 06:11

R Sahu