C ++模板专业化语法 [英] C++ templates specialization syntax

查看:199
本文介绍了C ++模板专业化语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ Primer Plus(2001,Czech Translation)中,我发现了这些不同的模板特化语法:



function template

 模板< typename T> void foo(T); 

专业化语法

  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一点,我发现只有No.3的例子。他们之间有什么区别(在调用,编译,使用)?其中有些是过时的还是过时的?为什么不使用第一?

解决方案

以下是每种语法的注释:

  void foo(int param); //不是一个特殊化,它是一个重载

void foo< int>(int param); // ill-formed

//这种形式总是工作
template<> void foo< int>(int param); //显式专门化

//与上面一样,但只有在模板参数可以扣除时才有效!
模板<> void foo(int param); //显式专门化

//与上面一样,但只有在模板参数可以扣除时才有效!
template void foo(int param); //显式实例化






p>

  //注意< int> ;.这种形式总是工作! 
template void foo< int>(int param); // explicit instantiation

//注意<> ;.只有模板参数扣除是可行的!
template void foo<>(int param); //显式实例化








因此,不要使函数模板特殊化:





em>显式实例化
  • >


    查看此:




    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?

    解决方案

    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 :

    这篇关于C ++模板专业化语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆