Skip to Content
Hands-On Design Patterns with C++
book

Hands-On Design Patterns with C++

by Fedor G. Pikus
January 2019
Intermediate to advanced
512 pages
14h 5m
English
Packt Publishing
Content preview from Hands-On Design Patterns with C++

Type erasure in C++

Let's finally see how std::shared_ptr does its magic. We will do it with a simplified example of a smart pointer that focuses specifically on the type erasure aspect. It should not surprise you to learn that this is done with a combination of generic and object-oriented programming:

template <typename T>class smartptr {    struct deleter_base {        virtual void apply(void*) = 0;        virtual ~deleter_base() {}    };    template <typename Deleter>     struct deleter : public deleter_base {        deleter(Deleter d) : d_(d) {}        virtual void apply(void* p) { d_(static_cast<T*>(p)); }        Deleter d_;    };    public:    template <typename Deleter>         smartptr(T* p, Deleter d) :            p_(p), d_(new deleter<Deleter>(d)) {}    ~smartptr() { d_->apply(p_); delete d_; } T* operator->() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Structural Design Patterns in Modern C++

Structural Design Patterns in Modern C++

Umar Lone

Publisher Resources

ISBN: 9781788832564Supplemental Content