zoukankan      html  css  js  c++  java
  • C++ templete: "class" vs "typename" in a templateparameter

    C++03标准说,class和typename没有啥区别:There is no semantic difference between class and typename in a template-parameter

    Stan Lippman在他的博客[Ref StanL]中这么说. 这是一个历史遗留问题。最初,Stroustrup也许为了不破坏已经存在的代码,所以重用了class这个已有的关键字。
    但毫无疑问class这个关键字很迷惑人,会让初学者觉得在template里只能使用class,而不能使用其他built-in type. 并且在ISO C++标准化过程中,在模板的定义中存在一个异议。
    template <class T>
    class Demonstration {
    public:
    void method() {
        T::A *aObj; // oops … <==what's this??
         // …
    };

    这里的目的是申明了一个T::A*类型的局部变量aObj,但是编译器的语法会认为这里是T中的static变量T::A乘以aObj.
    于是标准委员会决定增加了一个新的关键字,typename. 他的意思就如他的名字,非常直白。就像这样
    typename T::A* a6; // declare pointer to T’s A
    Scott Myers在Effective C++(3rd ed.)的第42条说, class和typename在申明一个模板的类型参数的时候,没有区别。
    template<class T> class Widget;                 // uses "class"
    template<typename T> class Widget;              // uses "typename"

    但是在指明模板的嵌套类型的时候,只能用typename, 就比如
    template <class T>
    class Dem{
    public:
          void foo()  {
                typename T::A * aObj;
          }
    };

    在显式的实例化一个模板的时候,只能用class
    template class Foo<int>;
    [Ref StanL]Why C++ Supports both Class and Typename for Type Parameters(http://blogs.msdn.com/b/slippman/archive/2004/08/11/212768.aspx)


  • 相关阅读:
    pstree
    gvisor vfs2
    gvisor entersyscall exitsyscall
    gvisor在arm64下syscall.SIGILL信号处理
    SpringBlade 为id添加自增长属性
    SQL Server Update 一个列的数据为随机数
    SpringBlade Saber 关闭验证码
    SpringBlade Saber 用户列表的新增按钮 是怎么个显示原理
    SpringBlade Saber 切换标签页 不刷新
    SpringBlade 00 常见问题汇总
  • 原文地址:https://www.cnblogs.com/aoaoblogs/p/2096280.html
Copyright © 2011-2022 走看看