C++ templates specialization syntax

Jan Turoň picture Jan Turoň · Nov 30, 2011 · Viewed 33.7k times · Source

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?

Answer

Nawaz picture Nawaz · Nov 30, 2011

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 :