How do I create an instance of a composite templated upon a different type?

M

mat

I am creating composite objects from various building blocks. This is best
described with an example.

template <class T>
class Behavior
{
public:

virtual void DoSomething(T& t) = 0;

virtual void AddChild(Behavior<T>* child){}
};

//------------------------------------------------------------------

template <class T>
class CompositeBehavior : public Behavior<T>
{
list<Behavior<T> > children;

public:

virtual void DoSomething(T& t) = 0;

virtual void AddChild(Behavior<T>* child){children.push_back(child);}
};

//-------------------------------------------------------------------

template <class T>
class SelectBehavior : public Composite<T>
{
void DoSomething(T& t) ;
};

//-------------------------------------------------------------------

template <class T>
class ConcreteBehavior : public Behavior<T>
{
void DoSomething(T& t) ;
};

So I create a composite out of these building blocks.

Behavior<Dog>* pDogRoot = new SelectBehavior<Dog>();
pDogRoot ->AddChild(new ConcreteBehavior<Dog>());
pDogRoot ->AddChild(new ConcreteBehavior<Dog>());

I'd like to be able to create an instance of this composite as though it was
created using a different type, say a Cat, but without going through the
process of creating it all over again by hand (the composites can get
complex). Ideally I'd like to be able to pass some function pRoot and it
return an instance created for the specified type.

Behavior<Cat>* pCatRoot = MakeInstance<Cat>(pDogRoot);

How could i go about doing this? What design patterns might be relevent? (is
it even possible?)

Many thanks for any help.
 

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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top