C++ templates specialization syntax

后端 未结 2 1385
猫巷女王i
猫巷女王i 2020-11-28 03:00

In C++ Primer Plus (2001, Czech Translation) I have found these different template specialization syntax:

function template

template         


        
相关标签:
2条回答
  • 2020-11-28 03:15

    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
    
    0 讨论(0)
  • 2020-11-28 03:24

    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
    0 讨论(0)
提交回复
热议问题