[英]Nested class forward declaration for template inheritance
What's the proper way to inherit from a template class with the template argument being a nested class within the inheriting class? 从模板类继承而模板参数是继承类中的嵌套类的正确方法是什么?
class SomeClass : public TemplateClass<NestedClass>
{
class NestedClass {};
};
There's no way to do specifically that. 没有办法专门这样做。 If you really have to inherit from
TemplateClass<NestedClass>
, you'll have to move the NestedClass
declaration out of SomeClass
. 如果确实必须继承自
TemplateClass<NestedClass>
,则必须将NestedClass
声明移出SomeClass
。
I can't see how you could do this properly. 我看不到您如何正确执行此操作。 There is this:
有这个:
template<class T> class TemplateClass {};
class NestedClass {};
class SomeClass : public TemplateClass<NestedClass>
{
typedef NestedClass NestedClass;
};
but that's just faking it... 但这只是伪装...
You must atleast forward declare the NestedClass: 您必须至少向前声明NestedClass:
class NestedClass;
template<class T> class TemplateClass{};
class SomeClass : public TemplateClass<NestedClass>
{
class NestedClass{};
};
This works. 这可行。 Tested on MinGW c++ on windows.
在Windows上的MinGW c ++上进行了测试。
Update: @jon I tried the following on with gcc version 3.4.5 on Windows XP: 更新:@jon我在Windows XP的gcc版本3.4.5上尝试了以下操作:
#include <iostream>
class NestedClass;
template<class T> class TemplateClass{};
class SomeClass : public TemplateClass<NestedClass>
{
public:
class NestedClass{
public:
int a;
static int test(){ return 100; }
};
NestedClass nc;
};
int main(){
SomeClass sc;
sc.nc.a = 10;
std::cout<< sc.nc.a << std::endl;
std::cout<< sc.nc.test() << std::endl;
}
And, I get the following output: 10 100 而且,我得到以下输出:10 100
But, I guess what the author intended (like @jon suggested) is actually this: 但是,我想作者的意图(像@jon建议的)实际上是这样的:
class SomeClass::NestedClass;
template<class T> class TemplateClass{};
class SomeClass : public TemplateClass<SomeClass::NestedClass>
{
public:
class NestedClass{};
NestedClass nc;
};
And this does not work. 这是行不通的。 The reason being that to be able to declare SomeClass::NestedClass in the template specification, SomeClass should have been declared.
原因是为了能够在模板规范中声明SomeClass :: NestedClass,应该已经声明了SomeClass。 But, we are trying to do exactly that - hence we get a cyclic dependency.
但是,我们正试图做到这一点-因此我们得到了循环依赖。
So I guess @jon's answer best solves this problem. 所以我猜@jon的答案最能解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.