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

Discussion in 'C++' started by mat, Dec 22, 2009.

  1. mat

    mat Guest

    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.
     
    mat, Dec 22, 2009
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. RA Scheltema
    Replies:
    3
    Views:
    410
    RA Scheltema
    Jan 6, 2004
  2. Marijn
    Replies:
    5
    Views:
    481
    Marijn
    Feb 13, 2004
  3. Replies:
    0
    Views:
    2,249
  4. Amadeus W. M.
    Replies:
    2
    Views:
    406
    Amadeus W. M.
    Jul 4, 2006
  5. debartsa
    Replies:
    1
    Views:
    264
    John Saunders
    Apr 23, 2004
Loading...

Share This Page