递归检查超级类Type_Info
-
12-12-2019 - |
题
有没有办法检查超类的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();
所以我不使用实例。我很乐意将目前的系统保持在锁定中。
解决方案
没有任何自动方法,即我知道。但是,如果我理解你,可以通过很少的努力来完成。
对于每个“基本”类,添加一个引用自身的键盘,而是在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";
}
.
其他提示
为什么不仅在基类生成的基础类生成的变量中创建一个不被任何派生类未修改的变量(除非您特别希望它)。它听起来不像你想要多态性,因为你希望比特值是相同的,无论派生类类型如何,而不是根据类型而异。如果在将来需要覆盖某种派生类型时,您仍然可以专门为该类执行此类。
或者,您可以在基类中使用虚拟函数返回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.
};
. 不隶属于 StackOverflow