Making virtual objects out of non-virtual objects
In my program I have a number of classes which implement the same
functionality, I use them in templated functions and classes. For
example:
struct A {
int foo() { return 1; }
};
struct B {
int foo() { return 1; }
};
This is all good, until one day I found in some cases I need to be able
to be able to be able to pass around an object whose type is not known
until run-time. However, I don't want to introduce virtual functions
and pass around pointers for the common case. So I decided to write a
wrapper, which looks like:
struct AnyVariable
{ tr1::shared_ptr<AnyPtr> p;
int foo() { return p->foo(); }
};
struct AnyPtr
{ virtual int foo() = 0; }
template<typename T>
struct AnyPtr_Concrete : public AnyPtr
{
T data;
virtual int foo() { return data.foo; }
};
With a little more nice wrapping, and neatening, I can now write:
AnyVariable(new AnyPtr_Concrete<A>(A)), and be able to pass around
objects that look like normal non-virtual classes, but act like
pointers to a virtual type heirachy.
I have two questions. Has anyone described this before, and can anyone
see a better way of doing thing?