使用成员类型的模板类作为类成员变量的类型 [英] Using a member type of templated class as the type of a class member variable
问题描述
为什么下面没有编译(MSVC10 - 但我怀疑它不是有效的C ++),并有一个解决方法?
Why does the following not compile (MSVC10 - but I suspect it's not valid C++), and is there a workaround?
template <typename M>
struct MyClass
{
typedef std::vector<M>::iterator iteratorT;
iteratorT myIterator;
};
错误是错误C2146:语法错误: iteratorT'
。我已经尝试了一组具有相同结果的变体:可以使用 std :: vector< M> :: iterator
作为成员函数中的类型,
Error is error C2146: syntax error : missing ';' before identifier 'iteratorT'
. I've tried a bunch of variations with the same result: you can use std::vector<M>::iterator
as a type in a member function, but not as a type of a member variable.
推荐答案
这是一个 typename
。简单的答案,你需要这样做:
It's a case of the typename
. Short answer, you need to do this instead:
typedef typename std::vector< M >::iterator iteratorT;
答案很长,编译器不知道 std :: vector< M> :: iterator
解析为 M
可以是任何东西,可以有 std :: vector
。具体来说,它不能判断 std :: vector< M> :: iterator
是一个类型或值,它相信它的值。你必须通过插入 typename
来显式地告诉编译器它的类型。
Long answer, the compiler doesn't know what std::vector< M >::iterator
resolves to as M
can be anything and there could be a specialization of std::vector
for it. Specifically, it cannot tell if std::vector< M >::iterator
is a type or a value, and it believes its a value. You have to explicitly tell the compiler its a type by inserting typename
.
这篇关于使用成员类型的模板类作为类成员变量的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!