Reputation: 534
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; 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.
Q: How can I enforce this method to accept only objects of base type 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.
Upvotes: 0
Views: 309
Reputation: 534
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 !
Upvotes: 0
Reputation: 157314
There is no direct way; type_info
is by design a minimal interface.
I'd suggest you rewrite getBit
as a template function callable as getBit<MyComponentClass>()
. You can then check base types in the template (e.g. 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.
Upvotes: 2
Reputation: 10557
You are right. Any derivative can be passed. C++ Language does not have features for this type of restriction. 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.
Upvotes: 0