有没有办法检查超类的type_info是什么? 在我的系统中,对象由一组位标识。哪个是由type_info哈希码识别的。我希望其中一些类型能够实现多态性,因为我的系统认为它们位于同一位。 type_info为每个类类型创建唯一的哈希码。相反,我希望派生类采用它们的超类的位集,如下所示:
Component > ISomeInterfaceComponent -> bit = 00001
|
\ ComponentContextA -> bit = ISomeInterFaceComponent bit
|
\ ComponentContextB -> bit = ISomeInterFaceComponent bit
|
\ ComponentContextC -> bit = ISomeInterFaceComponent bit
这应该将包含组件的对象添加到一个系统进行处理。
截至目前,这是发生的事情:
Component > ISomeInterFaceComponent -> bit = 00001
|
\ ComponentContextA -> bit = 00010
|
\ ComponentContextB -> bit = 00100
|
\ ComponentContextC -> bit = 01000
我要求为所有组件创建不同的系统。
如果有人能指点我如何实现这一目标,那就太好了。
编辑: 为了防止混淆为类型设置一点,它如下: ComponentTypeManager :: GETBIT();
所以我没有处理实例。我希望保持现有系统的锁定。
答案 0 :(得分:1)
我没有任何自动方式。但是,如果我理解你,可以通过一点额外的努力来完成。
对于每个“基础”类,添加一个引用自身的typedef,然后在typeid()
中使用它。注意,子类可以选择覆盖它。如果他们这样做,那么他们将获得自己的身份证,他们的孩子将使用他们的价值。
注意,另一个解决方案,如果你根本不想使用typeid()
,那么在基类上有一个静态成员(或成员函数),它返回基类的正确值,然后调用直接在你的getBit()函数中。
#include <iostream>
#include <iomanip>
#include <typeinfo>
struct Base1
{
typedef Base1 Base;
};
struct Base2
{
typedef Base2 Base;
};
struct Derived1A : public Base1 { };
struct Derived1B : public Base1 { };
struct Derived2A : public Base2 { };
struct Derived2B : public Base2 { };
template <typename T>
std::size_t getBit()
{
// Do whatever you normally do here, but use T::Base instead of T
return std::hash<std::string>()(typeid(typename T::Base).name());
}
int main()
{
std::cout << std::boolalpha << getBit<Derived1A>() << " == " << getBit<Derived1B>() << " " << (getBit<Derived1A>() == getBit<Derived1B>()) << "\n";
std::cout << std::boolalpha << getBit<Derived2A>() << " == " << getBit<Derived2B>() << " " <<(getBit<Derived2A>() == getBit<Derived2B>()) << "\n";
}
答案 1 :(得分:0)
为什么不在基类ISomeInterFaceComponent
中创建一个未被任何派生类修改的变量(除非您特别希望它)。这听起来并不像你想要多态,因为你想要比特值相同而不管派生类类型,而不是根据类型而变化。如果将来你需要覆盖if某个派生类型,你仍然可以专门为该类做这个。
或者你可以在基类中使用一个虚函数来返回一个int(比特值 - 或者它实际上是什么类型),并且只是不要在你希望具有相同比特值的派生类中覆盖它。基地。
例如
class ISomeInterFaceComponent {
virtual int GetBit() { return 1;}; // return bit value
};
class ComponentContextA : public ISomeInterFaceComponent {
// Do not override GetBit() - let the base class function get called.
};