Skip to content

Instantly share code, notes, and snippets.

@nixiz
Last active September 17, 2021 07:11
Show Gist options
  • Save nixiz/5a5cb9c0b36a2519976e24d7884252f5 to your computer and use it in GitHub Desktop.
Save nixiz/5a5cb9c0b36a2519976e24d7884252f5 to your computer and use it in GitHub Desktop.
#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();
}
@makifay
Copy link

makifay commented May 30, 2021

Merhaba, ClassA foo fonksiyonunda "}" eksik kalmış.

@nixiz
Copy link
Author

nixiz commented May 31, 2021

@makifay teşekkürler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment