Last modified on 3 June 2012, at 19:22

More C++ Idioms/Type Erasure

class TypeErasure {
    struct Concept {
        virtual ~Concept() {}
        virtual Concept* clone() const = 0;
        // Forwarding functions
        virtual void print() const = 0;
        virtual std::string str() const = 0;
    };
    template<typename T> struct Model : Concept {
        explicit Model(T const& data) : data(data) {}
        virtual Model* clone() const { return new Model(data); }
        // Forwarding functions
        virtual void print() const { return data.print(); }
        virtual std::string str() const { return data.str(); }
        T data;
    };
    boost::scoped_ptr<Concept> object;
public:
    template<typename T>
        explicit TypeErasure(T const& data) : object(new Model<T>(data)) {}
    TypeErasure(TypeErasure const& that) : object(that.object ? that.object->clone() : 0) {}
    // Forwarding functions
    void print() const { return object->print(); }
    std::string str() const { return object->str(); }
};

Source: http://zao.se/~zao/boostcon/10/2010_presentations/thu/type_erasure_pattern_boostcon.pdf