Last active
September 17, 2021 07:11
-
-
Save nixiz/5a5cb9c0b36a2519976e24d7884252f5 to your computer and use it in GitHub Desktop.
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
#include <iostream> | |
#include <string> | |
#include <memory> | |
#include <cassert> | |
template <class T> | |
class Singleton | |
{ | |
public: | |
using Type = typename std::remove_all_extents<T>::type; | |
template <typename ...Args> | |
Singleton(Args&& ...args) | |
{ | |
struct StaticObjCreator { | |
StaticObjCreator(std::unique_ptr<Type>& obj_ptr, Args&& ...arguments) { | |
assert(obj_ptr == nullptr); | |
obj_ptr.reset(new Type(std::forward<Args>(arguments)...)); | |
} | |
}; | |
static StaticObjCreator _creator(pointee, std::forward<Args>(args)... ); | |
assert(pointee != nullptr); | |
} | |
static Type *getInstance() { return pointee.get(); } | |
Type * operator->() { return &**this; } | |
const Type* operator->() const { return &**this; } | |
Type& operator *() { return *pointee; } | |
const Type& operator *() const { return *pointee; } | |
private: | |
static inline std::unique_ptr<Type> pointee = nullptr; | |
}; | |
class ClassA { | |
public: | |
ClassA() { std::cout << "ClassA::ClassA()" << std::endl; } | |
~ClassA() { std::cout << "ClassA::~ClassA()" << std::endl; } | |
void foo() { | |
std::cout << "ClassA::foo()" << std::endl; | |
} | |
}; | |
class ClassB { | |
public: | |
ClassB(int, double, std::string) {} | |
void foo() {} | |
void bar() {} | |
}; | |
int main() | |
{ | |
Singleton<ClassA> a; // -> can be instantiated like a normal class | |
Singleton<ClassA> aa; // -> aa will be referenced to a | |
Singleton<ClassB> b(1, 3.14, "hello world!"); // -> | |
a->foo(); | |
Singleton<ClassA>::getInstance()->foo(); | |
b->bar(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Merhaba, ClassA foo fonksiyonunda "}" eksik kalmış.