简体   繁体   English

type_info的C ++特定类型

[英]C++ specific type for type_info

Consider the following methods 请考虑以下方法

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();
}

I would call this as follows 我会这样称呼如下

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

Now as the ComponentManagerType suggests; 现在正如ComponentManagerType所暗示的那样; this is only meant for Components. 这仅适用于组件。 The problem as of right now is that any type can be passed. 现在的问题是任何类型都可以传递。 It won't do any harm but an id and bitset will be created for a non-component object. 它不会造成任何伤害,但会为非组件对象创建id和bitset。

Q: How can I enforce this method to accept only objects of base type Component? 问:如何强制此方法仅接受基类型Component的对象?

I know there is no direct way. 我知道没有直接的方法。 But I'm pretty much scratching my head over this. 但我对此非常感兴趣。

Edit: Added my own solution. 编辑:添加了自己的解决方案。 Not sure if it's kosher. 不确定它是否是犹太洁食。

There is no direct way; 没有直接的方法; type_info is by design a minimal interface. type_info是一个设计最小的接口。

I'd suggest you rewrite getBit as a template function callable as getBit<MyComponentClass>() . 我建议你将getBit重写为可调用为getBit<MyComponentClass>()的模板函数。 You can then check base types in the template (eg using boost::is_base_of ; you could even enforce the requirement in the template function declaration using std::enable_if ) and perform the typeid operation knowing that the base class is correct. 然后,您可以检查模板中的基类型(例如,使用boost :: is_base_of ;您甚至可以使用std :: enable_if在模板函数声明中强制执行该需求)并执行typeid操作,因为知道基类是正确的。

You are right. 你是对的。 Any derivative can be passed. 任何衍生物都可以通过。 C++ Language does not have features for this type of restriction. C ++语言没有此类限制的功能。 You can only make the method protected/private to narrow down the area of possible places of calls. 您只能使方法受保护/私有以缩小可能的呼叫区域的范围。 In smaller scope you have better chances to control the calls. 在较小的范围内,您有更好的机会控制呼叫。

template<typename component>
static bitset<BITSIZE> getBit(){

    //Check if we are being legal with components and shizzle
    Component * c = (component*)0;

    ComponentType & type = getTypeFor(typeid(component));
    return type.getBit();
}

This will throw a fatal error. 这会引发致命的错误。 If casting doesn't work. 如果铸造不起作用。 It simply means it's not a component. 它只是意味着它不是一个组件。

Not sure how this will fair though. 不知道这会如何公平。

But this seems to work ! 但这似乎有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM