#include <iostream>

        using namespace std;

        // Base of the trick: Data _and_ implementation of the feature.
        template <class Base>
        struct DimStuff : Base
        {
                DimStuff() : w(30) {}
                int width() const { return w; }
                void setWidth(int ww) { w = ww; }
                int w;
        };


        // Business as usual
        struct Inset
        {
                void metrics() { cout << width() << ' '; }
                // Note: no need to invent dummy implementions here.
                virtual int width() const = 0;
                virtual void setWidth(int) = 0;
                virtual ~Inset() {}
        };


        // Business as usual
        struct SlimInset : Inset
        {
                int width() const { return 42; }
                void setWidth(int) { cout << "cannot do that"; }
        };


        struct FatBase : Inset
        {
                // Note that we do not 'reimplement' widht/setWidth
                // at all. Nevertheless, we can 'use' it everywhere
                // (outside of constructors and destructor)
                void foo() { setWidth(20); cout << "foo: " << width() << " "; }
        };


        // We 'add' data _and_ implementation here. And we can do that
        // at any place in the normal hierarchy of insets.
        typedef  DimStuff<FatBase>  FatInset;

Looks good. Nice trick. Would the following be possible?

struct FatInset : DimStuff<WhatEverParentInset> {
}

Would there be any disadvantage of this? I think it's easier to understand.

One problem I see here: What about the constructors? They must be generic in DimStuff, no?

Stefan

Attachment: PGP.sig
Description: Signierter Teil der Nachricht

Reply via email to