使用父类定义的类型的基类
我有一个 Visual Studio 2008 C++ 应用程序,其中基类 A_Base
需要实例化其类型由父类定义的数据成员。例如:
template< typename T >
class A_Base
{
public:
typedef typename T::Foo Bar; // line 10
private:
Bar bar_;
};
class A : public A_Base< A >
{
public:
typedef int Foo;
};
int _tmain( int argc, _TCHAR* argv[] )
{
A a;
return 0;
}
不幸的是,编译器似乎不知道 T::Foo
是什么,直到为时已晚,我收到如下错误:
1>MyApp.cpp(10) : error C2039: 'Foo' : is not a member of 'A'
1> MyApp.cpp(13) : see declaration of 'A'
1> MyApp.cpp(14) : see reference to class template instantiation 'A_Base<T>' being compiled
1> with
1> [
1> T=A
1> ]
1>MyApp.cpp(10) : error C2146: syntax error : missing ';' before identifier 'Bar'
1>MyApp.cpp(10) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>MyApp.cpp(10) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
有没有办法实现这种类型的功能?
谢谢, 保罗·H
I have a Visual Studio 2008 C++ application where a base class A_Base
needs to instantiate a data member whose type is defined by a parent class. For example:
template< typename T >
class A_Base
{
public:
typedef typename T::Foo Bar; // line 10
private:
Bar bar_;
};
class A : public A_Base< A >
{
public:
typedef int Foo;
};
int _tmain( int argc, _TCHAR* argv[] )
{
A a;
return 0;
}
Unfortunately, it appears the compiler doesn't know what T::Foo
is until it's too late and I get errors like this:
1>MyApp.cpp(10) : error C2039: 'Foo' : is not a member of 'A'
1> MyApp.cpp(13) : see declaration of 'A'
1> MyApp.cpp(14) : see reference to class template instantiation 'A_Base<T>' being compiled
1> with
1> [
1> T=A
1> ]
1>MyApp.cpp(10) : error C2146: syntax error : missing ';' before identifier 'Bar'
1>MyApp.cpp(10) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>MyApp.cpp(10) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Is there any way to achieve this type of functionality?
Thanks,
PaulH
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
A_Base
在A
尚未完成的点实例化:您可以考虑使用特征类:
A_Base<A>
is instantiated at a point whereA
is not complete yet :You could consider using a traits class :
您可以尝试以下操作:
You can try the following:
类
A
依赖于类A_Base
,而类A_Base
又依赖于类A
...等等。这里有一个递归。您需要在单独的类中声明Foo
。另请参阅GotW #79。
Class
A
depends on classA_Base
which depends on classA
... etc. You have a recursion here. You need to declareFoo
in a separate class.See also GotW #79.