使用模板化类的成员类型作为类成员变量的类型

Using a member type of templated class as the type of a class member variable

本文关键字:成员 类型 变量 成员类      更新时间:2023-10-16

为什么以下内容无法编译(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<M>::iterator用作成员函数中的类型,但不能用作成员变量的类型。

这是

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

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

长答案,编译器不知道std::vector< M >::iterator解析为什么M可以是任何东西,并且可能有专门的std::vector。具体来说,它无法判断std::vector< M >::iterator是类型还是值,并且它认为它是一个值。您必须通过插入 typename 来显式告诉编译器它是一种类型。