A singleton template-based approach
from:Game Programming Using Qt, page 245.
A simple template-based approach would look like this (as a header file, singleton.h):
template <class T>
class Singleton
{
public:
static T& Instance()
{
static T _instance;
return _instance;
}
private:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton &) = delete;
Singleton& operator=(const Singleton &) = delete;
};
self define class:
class MyClass
{
public:
void print()
{
std::cout << "hello world" << std::endl;
}
};
In the source code, you will include that header file and acquire a singleton of a class called MyClass with:
#include <iostream>
#include "singleton.h"
int main(int argc, char **argv)
{
MyClass *singleton = &Singleton<MyClass>::Instance();
singleton->print();
return 0;
}