Reputation: 677
I am slightly confused about the syntax of explicit template specialization for functions.
Let's say I have the following:
template<class T>
void f(T t)
{}
I know that for an explicit specialization I need to supply template <>
as I otherwise get overloading. The following two compile:
// (a)
template<>
void f<int>(int t)
{}
//(b)
template<>
void f(int t)
{}
But, what is the difference between (a) and (b)?
Upvotes: 3
Views: 75
Reputation: 137330
As written, both do the same thing. Template argument deduction is used to figure out the type of T
in your explicit specialization. The "fun" starts when you have overloading function templates:
template<class T> //#1
void f(T t)
{}
template<class T> //#2
void f(T* t)
{}
template<>
void f<int*>(int* t) // specializes #1
{}
template<>
void f(int* t) // specializes #2, equivalent to void f<int>(int* t)
{}
And the real "fun" starts when you change the order:
template<class T> //#1
void f(T t)
{}
template<>
void f(int* t) // specializes #1, equivalent to void f<int*>(int* t)
{}
template<class T> //#2
void f(T* t)
{}
In this case, you get a counterintuitive result:
int *p;
f(p); // calls #2, not explicitly specialized #1
which is why it's usually better to use overloads rather than explicit specializations for function templates.
Upvotes: 5