Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does overload of template and non-template function with the "same signature" call the non-template function?

I have this code:

template<
    class T = const int &
> void f(T) {}

void f(const int &) {}

int main() {
   f(0);
}

Why does it call the second one instead of first? I would think of them as being the same but they're clearly not as I do not get a redefinition error.

like image 605
user2030677 Avatar asked Feb 02 '13 20:02

user2030677


People also ask

Can you overload a template function?

A template function can be overloaded either by a non-template function or using an ordinary function template.

How are overloaded functions and function templates alike How are they different?

Templates (normally) require that you use identical syntax to carry out the operations on all (supported) types. Function overloading is (or should be) used similarly, but allows you to use different syntax to carry out the operations for different types.

What is the relationship between function templates and overloading?

Function overloading is used when multiple functions do similar operations; templates are used when multiple functions do identical operations. Templates provide an advantage when you want to perform the same action on types that can be different.

Can we overload template functions with the same of arguments?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.


2 Answers

Because the second overload is not a template.

When a template function and a non-template function are both viable for resolving a function call, the non-template function is selected.

From Paragraph 13.3.3/1 of the C++ 11 Standard:

[...] Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then [...] F1 is a non-template function and F2 is a function template specialization [...]

like image 177
Andy Prowl Avatar answered Oct 03 '22 16:10

Andy Prowl


One is a template and the other is not, they are definitely not the same.

Overload resolution is designed to prefer a non-template over a templated function, everything else being equal.

like image 38
Bo Persson Avatar answered Oct 03 '22 17:10

Bo Persson