【发布时间】:2011-03-24 04:40:46
【问题描述】:
考虑这个伪代码:
class Foo {
public:
virtual int getID() const = 0;
}
template<typename T>
class Blah : public Foo {
public:
T data;
static const int ID; //static ID
int getID() const { return Blah<T>::ID; } //instance returns the ID
}
class Dude : public Blah<int> {
}
int Dude::ID = 10; //I want to define Blah<int>::ID here, but how?
int receive(const Foo& foo) {
if(foo.getID() == Dude::ID) {
cout << "Received a Dude" << endl;
}
}
这段代码无法编译,因为 ISO C++ 不允许将 Blah 模板中的 ID 定义为 Dude 类中的 ID。我明白为什么,因为我可以有多个扩展 Blah<int> 的类。
我明白如果我输入template<typename T> int Blah<T>::ID = 10' in the Blah<T> impl 它将起作用...但这不是我想要的...我希望派生类定义 ID...
我必须将 ID 和 getID() 推入派生类吗?我想最终我对一些 RTTI 感兴趣,所以我可以适当地处理Foo。如果有人有更好的模式,我会全力以赴。
编辑
作为对某些 cmets 的回应...我想通过某个 ID 唯一标识派生自 Foo 的类,以便我可以将某些 Foo 对象的运行时 ID 与特定的类 ID 进行比较。
谢谢!
【问题讨论】:
-
我不确定我是否正确理解了这个问题。你检查过CRTP吗?在这里可能有用。 en.wikipedia.org/wiki/Curiously_recurring_template_pattern
-
@Asha:我不熟悉 CRTP...但我不相信我想将 Dude 用作模板参数。
-
你问的是a step and not a goal,这就是it impossible to answer。你想完成什么?
-
@GMan:方便的链接...谢谢...我更新了我的问题。
-
@TReddy:可能我理解错了问题,但
typeid或dynamic_cast不符合目的吗?
标签: c++ templates inheritance rtti