I have a structure like the following:
struct managed_object {
virtual ~managed_object() { }
};
class trait1 {
public:
virtual void myMethod() const = 0;
};
class trait2 {
public:
virtual void myOtherMethod(int x) const = 0;
};
class MyType final : public managed_object, public trait1 {
...
};
class MyType2 final : public managed_object, public trait1, public trait2 {
...
};
class wrapper {
private:
managed_object* ptr;
public:
template<typename T> T* object() const {
return dynamic_cast<T*>(data.ptr);
}
};
So basically I have a managed_object base class from which multiple types inherit. Each of this subtypes can inherit from any combination of traits and they are final so that I'm sure they won't have any deeper level on inheritance.
The code works thanks to RTTI which takes the load of gluing everything together but at a price, otherwise
wrapper w = ...
trait* asTrait1 = w.object<trait1>;
wouldn't work because there's no direct relation between managed_object and trait1 types.
In my complete code I'm already sure that all dynamic_cast won't fail because I have additional data (not shown in the example) which provides me a sort of RTTI that is needed for other parts of the code.
Given that, is there a common pattern to solve the side-downcast problem without using the need of dynamic_cast and RTTI assuming that I can already know that a MyType class is inheriting from a specific trait? I'm trying to find a clever solution since it's a heavy bottleneck of the code.