【发布时间】:2014-04-05 14:54:03
【问题描述】:
鉴于此代码:
template < int I >
class Foo
{
public:
int v;
Foo() { v = I; }
virtual ~Foo() {}
};
class Bar : public Foo<0>, public Foo<3>
{
public:
template < int I >
int getValue() { return Foo<I>::v; }
};
int main() {
Bar b;
cout << b.getValue<0>() << endl; // prints 0
cout << b.getValue<3>() << endl; // prints 3
cout << b.getValue<4>() << endl; // compiler error
return 0;
}
是否可以遍历所有 Foo<i> 继承自 Bar 的类?我们可以假设 i 介于 0 和某个最大值 N 之间。在伪代码中:
for ( int i = 0; i < N; i++ )
{
if ( Bar inherits from `Foo<i>` )
{
cout << Foo<i>::v << endl;
}
}
【问题讨论】:
-
如果您在
i上有一个上限,那么您可以编写一个递归函数模板,为0 和您的上限之间的每个i值调用boost::is_base_of<YourClass, Foo<i> >。
标签: c++ templates inheritance reflection multiple-inheritance