May 2017
Intermediate to advanced
590 pages
17h 18m
English
There might be situations in larger code bases where you need more than one singleton type. In order to avoid writing the same pattern several times, you can implement it in a generic way. For this, we need to employ the curiously recurring template pattern (or CRTP) seen in the previous recipe. The actual singleton is implemented as a class template. The instance() method creates and returns an object of the type template parameter, which will be the derived class:
template <class T> class SingletonBase { protected: SingletonBase() {} public: SingletonBase(SingletonBase const &) = delete; SingletonBase& operator=(SingletonBase const&) = delete; static T& instance() { static T single; return single; } }; class Single : public ...Read now
Unlock full access