Making virtual objects out of non-virtual objects

4

4zumanga

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?
 
M

Michiel.Salters

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.

The creation looks like it could use a bit of wrapping, i.e.
template<typename T> AnyVariable::AnyVariable(T t) {
tr1::shared_ptr<AnyPtr>(new AnyPtr_Concrete<T> ptr);
ptr->data = t;
this->p = ptr;
}

You can now write
AnyVariable x = A(5);

Personally, I think AnyPtr is a misleading name. It's not a pointer,
but
an abstract base class. Furthermore, if you're careful, you can use
std::auto_ptr<AnyPtr> instead. I don't think AnyVariable's should
behave
like pointers and share state when copied - just clone the pointed-to
object.

HTH,
Michiel Salters
 
D

Diego Martins

In my program I have a number of classes which implement the same
functionality, I use them in templated functions and classes. For
example:
[chomp]

I have two questions. Has anyone described this before, and can anyone
see a better way of doing thing?

read Modern C++ Design from Alexandrescu

on first chapter, he describes many issues concerning to policy design
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top