gpt4 book ai didi

type_info 的 C++ 特定类型

转载 作者:行者123 更新时间:2023-11-28 03:35:01 25 4
gpt4 key购买 nike

考虑以下方法

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com