type_info 的 C++ 特定类型

标签 c++ typeinfo

考虑以下方法

static ComponentType & getTypeFor(const type_info &t){
        ComponentType * type = componentTypes[t.hash_code()];

        if(type == NULL)
        {
            type = new ComponentType();
            componentTypes[t.hash_code()] = type;
        }
        return *type;
};

static bitset<BITSIZE> getBit(const type_info &t){
    ComponentType & type = getTypeFor(t);
    return type.getBit();
}

我会这样调用它

ComponentManagerType::getBit(typeid(MyComponentClass)); 
// Not an instance, passing class name

现在按照 ComponentManagerType 的建议;这仅适用于组件。目前的问题是任何类型都可以传递。它不会造成任何伤害,但将为非组件对象创建一个 id 和 bitset。

问: 我如何强制此方法只接受基本类型组件的对象?

我知道没有直接的方法。但我对此几乎摸不着头脑。

编辑: 添加了我自己的解决方案。不确定它是否符合犹太洁食。

最佳答案

没有直接的方法; type_info设计上是一个最小的界面。

我建议你重写 getBit作为可调用为 getBit<MyComponentClass>() 的模板函数.然后您可以检查模板中的基本类型(例如使用 boost::is_base_of ;您甚至可以使用 std::enable_if 强制执行模板函数声明中的要求)并执行 typeid知道基类是正确的操作。

关于type_info 的 C++ 特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11181814/

相关文章:

c++ - 用不重复的随机数填充 vector 。为什么不工作?

c++ - GTKMM 错误 : Void Value Not Ignored As it Ought to Be

c++ - Win32 中的 RGB 后台缓冲区

c - 变量的类型是否存储在某处?它在哪里?

c++ - 检查字符串的类型信息时出现奇怪的输出

c++ - 使用 While 循环

c++ - D3D11Texture2D到具有不同上下文和设备的另一个纹理

c++ - 尝试计算派生类的实例,type_id 不起作用

c++ - 获取对象的类型

c++ - g++ 链接器错误——类型信息,但不是 vtable