什么时候`typename`不能被`class`取代?

时间:2011-11-14 01:50:35

标签: c++ templates

  

可能重复:
  C++ difference of keywords 'typename' and 'class' in templates

在很多情况下,我已经知道class无法替换typename。我只是在谈论相反的事情:用typename替换class

有人指出这里只能使用typename

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

但是我在这里用typename替换class没有任何问题(在MSVC中)。 回顾一下,我可以一直用class替换typename吗?如果没有,请举例。

2 个答案:

答案 0 :(得分:4)

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

name disambiguation 需要两个关键字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才能在这些角色中发挥作用;你不能用其他任何东西来代替。

答案 1 :(得分:0)

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

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

这是因为只能对模板进行模板化。

相关问题