In C++ Primer Plus (2001, Czech Translation) I have found these different template specialization syntax:
function template
template <typename T> void foo(T);
specialization syntax
void foo(int param); // 1
void foo<int>(int param); // 2
template <> void foo<int>(int param); // 3
template <> void foo(int param); // 4
template void foo(int param); // 5
Googling a bit, I have found only No.3 examples. Is there any difference (in call, compiling, usage) among them? Are some of them obsolete/deprecated? Why not just use No.1?
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
What is the syntax to use explicit class specialization? Explanation: The class specialization is creation of explicit specialization of a generic class. We have to use template<> constructor for this to work. It works in the same way as with explicit function specialization.
Explicit (full) specializationAllows customizing the template code for a given set of template arguments.
Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type.
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:
And to know the terminologies:
See this :
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
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