首页 文章

什么时候`typename`不能被`class`取代? [重复]

提问于
浏览
3

可能重复:模板中关键字'typename'和'class'的C差异

在很多情况下我已经知道 class 不能被 typename 取代 . 我只是在谈论相反的事情:将 typename 替换为 class .

有人指出这里只能使用 typename

template<class param_t> class Foo 
{     
        typedef typename param_t::baz sub_t; 
};

但我没有看到在这里用 class 替换 typename 有任何问题(在MSVC中) . 总结一下,我可以一直用class替换typename吗?如果没有,请举例 .

2 回答

  • 0

    您不能将typename用于模板模板参数:

    template <
        template <typename> class Container>, // cannot use typename for class
        typename T
      > struct TestMe
    {
        Container<T> _data;
        // ... etc.
    };
    

    这是因为只有类可以模板化 .

  • 4

    不,你不能总是用另一个替换一个 .

    名称消除歧义需要两个关键字 typenametemplate ,以通知编译器依赖名称是否为值(不需要关键字),类型(需要 typename )或模板(需要 template ):

    template <typename T> struct Foo
    {
      char bar()
      {
        int x = T::zing;                 // value, no decoration for disambiguation of "T::zing"
    
        typedef typename T::bongo Type;  // typename, require disambiguation of "T::bongo"
    
        return T::template zip<Type>(x); // template, require disambiguation of "T::zip"
      }
    };
    

    只有关键字 typenametemplate 才能在这些角色中工作;你无法用其他任何东西取而代之 .

相关问题