4

Can I change this code to make it work? Is it possible to combine template method pattern and multiple inheritance? It seems to be very convenient to implement different algorithms in different classes. Thank you.

class TBase {
public:
    virtual void Do1() const = 0;
    virtual void Do2() const = 0;

    void Do() const {
        Do1();
        Do2();
    }
};

class TFirstAlgorithm {
public:
    void Do1() const {}
};

class TSecondAlgorithm {
public:
    void Do2() const {}
};

class TAlgorithm
    : public TBase
    , public TFirstAlgorithm
    , public TSecondAlgorithm
{};
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
typedef
  • 1,800
  • 3
  • 11
  • 19

2 Answers2

3

Fundamentally, your problem is that TFirstAlgorith::Do1 isn't related to TBase::Do1 (and likewise TSecondAlgorithm::Do2 to TBase::Do2.

One possible way to fix that would be to make them related:

class TBase {
public:
    virtual void Do1() const = 0;
    virtual void Do2() const = 0;

    void Do() const {
        Do1();
        Do2();
    }
};

class TFirstAlgorithm : public virtual TBase {
public:
    void Do1() const { }
};

class TSecondAlgorithm : public virtual TBase {
public:
    void Do2() const { }
};

class TAlgorithm
    : public TFirstAlgorithm
    , public TSecondAlgorithm
{};
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Btw, here is the problem: we cannot create objects of classes TFirstAlgorithm and TSecondAlgorithm. This is not so good beacause we cannot test them separately al least. – typedef Jun 09 '12 at 05:27
  • @user1058588: Yes, a class needs to define all pure virtual functions in the base class before it can be instantiated. There are workarounds (mostly introducing some other class that defines the others as NOPs), but none that's particularly clean. – Jerry Coffin Jun 09 '12 at 05:51
0

You can use implementations for Do1 and Do2 and call appropriate algorithm inside them.

 class TBase {
    public:
        virtual void Do1() const = 0;
        virtual void Do2() const = 0;

    void Do() const {
        Do1();
        Do2();
    }
};

class TFirstAlgorithm {
public:
    void Do1() const {}
};

class TSecondAlgorithm {
public:
    void Do2() const {}
};

class TAlgorithm
    : public TBase
    , public TFirstAlgorithm
    , public TSecondAlgorithm
{
   virtual void Do1() const { TFirstAlgorithm::Do1() ; }
   virtual void Do2() const { TSecondAlgorithm::Do2() ; }  
};
Kamran Amini
  • 1,062
  • 8
  • 14
  • Well, I have a lot of implementations of different functions Do1 and Do2. And I would like to combine them very easy to get different classes like TAlgorithm. But this solution makes me write these lines in each TAlgorithm class. – typedef Jun 08 '12 at 21:24