Last active
June 22, 2020 09:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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