C++ templates specialization syntax
Solution 1:
Here are comments with each syntax:
void foo(int param); //not a specialization, it is an overload
void foo<int>(int param); //ill-formed
//this form always works
template <> void foo<int>(int param); //explicit specialization
//same as above, but works only if template argument deduction is possible!
template <> void foo(int param); //explicit specialization
//same as above, but works only if template argument deduction is possible!
template void foo(int param); //explicit instantiation
Added by me:
//Notice <int>. This form always works!
template void foo<int>(int param); //explicit instantiation
//Notice <>. works only if template argument deduction is possible!
template void foo<>(int param); //explicit instantiation
From coding point of view, overload is preferred over function-template-specialization.
So, don't specialize function template:
- Why Not Specialize Function Templates?
- Template Specialization and Overloading
And to know the terminologies:
- instantiation
- explicit instantiation
- specialization
- explicit specialization
See this :
- Difference between instantiation and specialization in c++ templates
Solution 2:
Using Visual Studio 2012, it seems to work slightly different if there's no function argument:
template <typename T> T bar( );
//template int bar<int>( ) { return 0; } doesn't work
template < > int bar<int>( ) { return 0; } //does work