c++syntaxtemplate-specialization

What is the correct syntax for defining a specialization of a function template?


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?


Solution

  • 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 :