Using abstract base to implement private parts of a template class?

Posted by StackedCrooked on Stack Overflow See other posts from Stack Overflow or by StackedCrooked
Published on 2011-02-26T23:13:42Z Indexed on 2011/02/26 23:25 UTC
Read the original article Hit count: 167

Filed under:

When using templates to implement mix-ins (as an alternative to multiple inheritance) there is the problem that all code must be in the header file. I'm thinking of using an abstract base class to get around that problem. Here's a code sample:

class Widget
{
public:
    virtual ~Widget() {}
};

// Abstract base class allows to put code in .cpp file.
class AbstractDrawable
{
public:
    virtual ~AbstractDrawable() = 0;

    virtual void draw();

    virtual int getMinimumSize() const;
};

// Drawable mix-in
template<class T>
class Drawable : public T,
                 public AbstractDrawable
{
public:
    virtual ~Drawable() {}

    virtual void draw()
    { AbstractDrawable::draw(); }

    virtual int getMinimumSize() const
    { return AbstractDrawable::getMinimumSize(); }
};

class Image : public Drawable< Widget >
{
};


int main()
{
    Image i;
    i.draw();
    return 0;
}

Has anyone walked that road before? Are there any pitfalls that I should be aware of?

© Stack Overflow or respective owner

Related posts about c++