C++ templates specialization syntax

C++Template Specialization

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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:

  • instantiation
  • explicit instantiation
  • specialization
  • explicit specialization

See this :

Solution 2 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJan TuroňView Question on Stackoverflow
Solution 1 - C++NawazView Answer on Stackoverflow
Solution 2 - C++gerardwView Answer on Stackoverflow