Short version: Perfect C++11 Singleton Template


Long version:

Singleton is one of the widely adopted design patterns to encapsulate a service class or any class whose functionalities tightly bind to one particular instance.

It varies a lot in different programming languages to implement a singleton class. Most of them are tedious, and done in copy-and-paste way. C++, yes, the old one, is even more tedious to do so.

Fortunately, C++11 makes great efforts to transform the old C++ into a much modern one, or modern C++.

Thanks to the powerful template class in old C++ and perfect forward ability provided by C++11, a perfect C++11 singleton template class makes its way! Any C++ class with public constructor(s) can have a singleton version by just one line of declaration.


Example tells everything.

In AServiceClass.hpp

#include "Singleton.hpp"
...
class AServiceClass {
public:
    AServiceClass(); // default constructor
    AServiceClass(int a, int b); // parameterized constructor
    void provideService(); 
    ...
};
 
typedef Singleton<AServiceClass> ServiceClassSingleton; // Singleton in just one line !

In service-caller.cpp

#include "AServiceClass.hpp"
...
void callService_default() {
    ServiceClassSingleton::getInstance().provideService(); // call the singleton class!
}
...
void callService_with_parameter() {
    ServiceClassSingleton::getInstance(2018,211).provideService(); // call the parameterized version.
}
...