Skip to content

Instantly share code, notes, and snippets.

@neugen86
Last active January 29, 2020 08:17
Show Gist options
  • Save neugen86/78504c61ac5f2867a98dc860da7851c3 to your computer and use it in GitHub Desktop.
Save neugen86/78504c61ac5f2867a98dc860da7851c3 to your computer and use it in GitHub Desktop.
Dependency tool
#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