问题
I am developing a big hierarchy of classes for a framework that will require quite a lot of type casting when it gets done.
My question is, how stupid of an idea is to put in a static member that uses an enum to store all the object types in the hierarchy. Having the member static for every class will not increase the instanced object sizes, and will give a (potentially) faster way to determined the type of an object during runtime than dynamic_cast.
At least that's the basic idea. How adequate would this approach be, and are there any potential flaws?
回答1:
I don't know how you were gonna determine the type of each object from a static variable that is shared between the objects. Unless you have some virtual function that you override for each class, but then you don't need the static variable at all, just do something like this:
struct Base
{
virtual int type() = 0;
};
struct Derived1 : public Base
{
virtual int type() { return 1; }
};
struct Derived2 : public Base
{
virtual int type() { return 2; }
};
Not the fastest solution, but several magnitudes faster than dynamic_cast
or typeid
.
回答2:
Here is a slightly better and different answer. I didn't wanted to change Timo's answer so submitted a new one. Rationale behind this is to avoid magic numbers. Sometimes typecasting and fiddling with objects is necessary to add new functionality when the aim is not to modify the original classes. But this should not allow someone to use magic numbers.
enum mytypeid {
DERIVED1,
DERIVED2,
};
struct Base
{
virtual mytypeid type() = 0;
};
struct Derived1 : public Base
{
static const mytypeid mytype = DERIVED1;
virtual mytypeid type() { return mytype ; }
};
struct Derived2 : public Base
{
static const mytypeid mytype = DERIVED2;
virtual mytypeid type() { return mytype ; }
};
//...
void fn(Base &a) {
if(a.type() == Derived1::mytype) {
std::cout<<"1"<<std::endl;
}
}
来源:https://stackoverflow.com/questions/10216398/c-dynamic-cast-vs-storing-object-type-in-a-static-enum