C++ dynamic type construction and detection
- by KneLL
There was an interesting problem in C++, but it concerns more likely architecture.
There are many (10, 20, 40, etc) classes that describe some characteristics (mix-in classes), for exmaple:
struct Base { virtual ~Base() {} };
struct A : virtual public Base { int size; };
struct B : virtual public Base { float x, y; };
struct C : virtual public Base { bool some_bool_state; };
struct D : virtual public Base { string str; }
// ....
Primary module declares and exports a function (for simplicity just function declarations without classes):
// .h file
void operate(Base *pBase);
// .cpp file
void operate(Base *pBase)
{
// ....
}
Any other module can has a code like this:
#include "mixins.h"
#include "primary.h"
class obj1_t : public A, public C, public D {};
class obj2_t : public B, public D {};
// ...
void Pass()
{
obj1_t obj1;
obj2_t obj2;
operate(&obj1);
operate(&obj2);
}
The question is how to know what the real type of given object in operate() without dynamic_cast and any type information in classes (constants, etc)? Function operate() is used with big array of objects in small time periods and dynamic_cast is too slow for it. And I don't want to include constants (enum obj_type { ... }) because this is not OOP-way.
// module operate.cpp
void some_operate(Base *pBase)
{
processA(pBase);
processB(pBase);
}
void processA(A *pA)
{
}
void processB(B *pB)
{
}
I cannot directly pass a pBase to these functions. And it's impossible to have all possible combinations of classes, because I can add new classes just by including new .h files.
As one of solutions that comed to mind, in editor application I can use a composite container:
struct CompositeObject
{
vector<Base *pBase> parts;
};
But editor does not need a time optimization and can use dynamic_cast for parts to determine the exact type. In operate() I cannot use this solution.
So, is it possible to not use a dynamic_cast and type information to solve this problem? Or maybe I should use another architecture?