The correct way to explicitly specialize a function template is
I'm a little confused about the syntax of the explicit specialized specialization for functions.
Let's say I have the following:
template<class T>
void f(T t)
{}
I know that for explicit specialization I need to deliver template <>
as I otherwise get overload. The following two compilers:
// (a)
template<>
void f<int>(int t)
{}
//(b)
template<>
void f(int t)
{}
But what is the difference between (a) and (b)?
source to share
As written, both do the same. Template argument inference is used to define the type T
in your explicit specialization. The "fun" starts when you overload functional 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 will get an inconsistent result:
int *p;
f(p); // calls #2, not explicitly specialized #1
therefore, it is usually better to use overloads rather than explicit specializations for function templates.
source to share