Skip to content

Instantly share code, notes, and snippets.

@EgoPingvina
Last active June 22, 2020 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EgoPingvina/db5b43f00d3e1afb14a39feb0ade2078 to your computer and use it in GitHub Desktop.
Save EgoPingvina/db5b43f00d3e1afb14a39feb0ade2078 to your computer and use it in GitHub Desktop.
Implementation of a generic singleton template on C++. It allows turning any class to singleton by one line.
#pragma once
/// <summary>
/// The singleton`s implementation to Insert into any other class.
/// </summary>
/// <typeparam name="T">The class which will be turned into Singleton.</typeparam>
/// <param name="Action">Actions to be taken in the default constructor.</typeparam>
#define Singleton(T, Action) \
protected: \
T() { (Action)(); } \
T(T const&) = delete; \
T& operator=(T const&) = delete; \
~T() = default; \
public: \
static T* Instance() \
{ \
static T instance; \
return &instance; \
} \
private: \
/*
* How to use it?
*/
class A
{
Singleton(A, [this](){ this->a = 5; })
int a;
public:
int Foo() { return this->a; }
}
auto instance = A::Instance();
auto value = instance->Foo();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment