Last active
January 29, 2020 08:17
-
-
Save neugen86/78504c61ac5f2867a98dc860da7851c3 to your computer and use it in GitHub Desktop.
Dependency tool
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 | |
#include <cassert> | |
#include <functional> | |
template <typename T> | |
class Injection final | |
{ | |
static T* s_ptr; | |
public: | |
class Scope final | |
{ | |
std::function<void()> m_finalizer; | |
public: | |
Scope(Scope&& other) = default; | |
Scope& operator=(Scope&&) = default; | |
Scope(const Scope&) = delete; | |
Scope& operator=(const Scope&) = delete; | |
explicit Scope(T* ptr) | |
: m_finalizer([]{ s_ptr = nullptr; }) | |
{ | |
assert(ptr && "injecting object is null"); | |
assert(!s_ptr && "object is already injected"); | |
s_ptr = ptr; | |
} | |
~Scope() | |
{ | |
if (m_finalizer) | |
m_finalizer(); | |
} | |
}; | |
T* operator->() const { return s_ptr; } | |
}; | |
template <typename T> | |
T* Injection<T>::s_ptr = nullptr; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment