I have two versions of program. First:
template<class T>
void f(T i, T j) = delete;
template<>
void f(int i, int j) {
cout << i << j << endl;
};
int main()
{
f(1.5, 2);
return 0;
}
And second:
template<class T>
void f(T i, T j) = delete;
void f(int i, int j) {
cout << i << j << endl;
};
int main()
{
f(1.5, 2);
return 0;
}
The first version won't compile because 1.5 and 2 have different types. In the second version I removed template<> so 1.5 will be converted to 1 and program will run successfully.
So, when we remove template<>, is it still template specialization, or is it something else? Is there any difference besides implicit type casting? Is it useful?
For a (unqualified) function invocation as f(1.5, 2) in your code the compiler builds a set of candidate functions which contains regular functions and functions generated from templates. A function template is not a function until the template arguments have been resolved and substituted. See overload resolution for full details.
f is function template and it cannot deduce T from arguments of type double and int. The template specialization isn't considered because template argument deduction failed. The viable set of functions is empty and the compilation fails to compile the call.
You can resolve T ambiguity for the compiler if you call it as f<int> but such a call considers f templates only (because you explicitly specify the template parameter).
If you make the full specialization of f not a template, it becomes an regular function. In this case the template argument deduction still fails as before, but now there is another function f and the set of candidate functions contains that one function f. It can be called with the supplied arguments because double is implicitly converted to int.
For functions parameters whose types aren't deduced from the argument types (i.e. the parameter type is not a template parameter or an explicitly specified template parameter) the compiler considers implicit conversion of argument types to function parameter types and double to int is in implicit conversion and that's why the call to overloaded function f succeeds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With