Why does overload of template and non-template fun

2019-01-14 21:35发布

问题:

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.

回答1:

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 [...]



回答2:

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.