c++使用内部类指针类型定义模板类的静态成员
我有一个像这里一样的模板类(在标头中),其中包含一个内部类和一个指向内部类的类型指针的静态成员,
template <class t> class outer {
class inner {
int a;
};
static inner *m;
};
template <class t> outer <t>::inner *outer <t>::m;
当我想定义该静态成员时,我说“错误:预期的构造函数、析构函数或类型转换在 '* 之前最后一行的“令牌”(mingw32-g++ 3.4.5)
I have a template class like here (in a header) with a inner class and a static member of type pointer to inner class
template <class t> class outer {
class inner {
int a;
};
static inner *m;
};
template <class t> outer <t>::inner *outer <t>::m;
when i want to define that static member i says "error: expected constructor, destructor, or type conversion before '*' token" on the last line (mingw32-g++ 3.4.5)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要限定
inner
类是一个类型名称,因为它依赖于模板参数,并且 C++ 编译器假定名称inner
在此上下文不是类型:基本原理:上行中的名称
inner
取决于类型名称t
。此时,C++ 编译器不知道inner
是什么,因为inner
名称的含义可能因t
的不同而不同。例如,假设代码中的其他位置有int
的outer
类的专用版本:现在,
outer::inner
不再命名类型;它命名一个成员变量。因此,在一般情况下,
outer::inner
的含义将是不明确的,C++ 会假设inner
不这样做,从而解决了这种歧义。命名一个类型。除非您这么说,否则请在其前面添加typename
前缀:typename external::inner
。 (在这种情况下,inner
被称为依赖名称,因为它取决于t
的确切类型。)You need to qualify that the
inner
class is a typename, since it’s dependent on a template parameter and the C++ compiler assumes that the nameinner
in this context is not a type:Rationale: the name
inner
in the above line depends on a type name,t
. The C++ compiler at this point doesn’t know whatinner
is, because the meaning of the nameinner
can differ depending ont
. For example, suppose that, somewhere else in the code, there is a specialized version of theouter
class forint
:Now,
outer<int>::inner
no longer names a type; it names a member variable.Thus, in the general case the meaning of
outer<t>::inner
would be ambiguous and C++ resolves this ambiguity assuming thatinner
does not name a type. Unless you say it does, by prefixing it withtypename
:typename outer<t>::inner
. (In this context,inner
is called a dependent name since it depends on the exact type oft
.)