【问题标题】:When can `typename` not be replaced by `class`? [duplicate]什么时候 `typename` 不能被 `class` 代替? [复制]
【发布时间】:2011-12-28 07:45:54
【问题描述】:

可能重复:
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; 
};

但我认为在这里(在 MSVC 中)用 class 替换 typename 没有任何问题。 回顾一下,我可以总是用类替换类型名吗?如果不是,请举个例子。

【问题讨论】:

  • 在上述情况下,您和某些编译器可能会有所不同:)
  • 能否请您澄清一下您的实际问题是什么?
  • "如果没有请举个例子。"你已经有了一个例子——对于依赖类型,你必须使用typename,这就是引入这个关键字的目的。
  • @Rio:不好。您可能使用 MSVC,它在标准需要的地方不需要 typename。您可以使用 class 可能是从 C 继承 struct x var; 语法的产物。这是一个红鲱鱼。

标签: c++ templates


【解决方案1】:

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

typenametemplate 这两个关键字是 name disambiguation 所必需的,以告知编译器依赖名称是否是 value(不需要关键字),a 类型(需要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, it's not allowed as soon as you use bar() 奇怪的是,如果直接在 Foo 内部使用(而不是在函数内部),似乎 class 而不是 typename 会起作用。
  • @iammilind:用class 代替typename,我的GCC 说,error: ‘class ****’ resolves to ‘**** {aka int}’, which is is not a class type。因此,您不能使用 class 作为通用消歧器。但是,您似乎可以使用它来显式地请求一种类类型。我不知道。
【解决方案2】:

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

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

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

【讨论】:

  • 我要问的是,当我不能使用 CLASS 时。我知道我不能使用 TYPENAME。请仔细检查我的问题。
  • @Rio:请仔细检查您的问题,看看您是否可以改进演示文稿!
猜你喜欢
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 2021-05-18
  • 1970-01-01
  • 2021-11-29
  • 2014-04-29
相关资源
最近更新 更多