【问题标题】:Using a member type of templated class as the type of a class member variable使用模板类的成员类型作为类成员变量的类型
【发布时间】:2012-05-25 13:59:01
【问题描述】:

为什么以下内容无法编译(MSVC10 - 但我怀疑它不是有效的 C++),是否有解决方法?

template <typename M>
struct MyClass
{
    typedef std::vector<M>::iterator iteratorT;

    iteratorT myIterator;

};

错误是error C2146: syntax error : missing ';' before identifier 'iteratorT'。我尝试了一堆变体,结果相同:您可以将std::vector&lt;M&gt;::iterator 用作成员函数中的类型,但不能用作成员变量的类型。

【问题讨论】:

标签: c++ templates


【解决方案1】:

这是typename 的情况。简短的回答,你需要这样做:

 typedef typename std::vector< M >::iterator iteratorT;

长答案,编译器不知道std::vector&lt; M &gt;::iterator 解析为什么,因为M 可以是任何东西,并且可能有std::vector 的专门化。具体来说,它无法判断std::vector&lt; M &gt;::iterator 是类型还是值,它相信它是一个值。您必须通过插入 typename 来明确告诉编译器它的类型。

【讨论】:

  • 天啊!白痴时刻。我已经习惯了 MSVC 不需要 typename,所以我倾向于将其视为 gcc 问题!
  • @Zero:是的,很遗憾 MSVC 没有正确实现两阶段模板查找。
猜你喜欢
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多