Created
April 17, 2019 12:57
-
-
Save sigman78/34b7e2ffa0024a0542d9e4197e797c89 to your computer and use it in GitHub Desktop.
Revisions
-
sigman78 created this gist
Apr 17, 2019 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,73 @@ #include <memory> #include <utility> #include <cassert> #include <iostream> template<typename Service> struct Registry { Registry() = delete; ~Registry() = delete; inline static bool empty() noexcept { return !bool{svc}; } template<typename Implementation=Service, typename... Args> inline static void assign(Args&& ...args) { svc = std::make_shared<Implementation>(std::forward<Args>(args)...); } inline static void reset() noexcept { svc.reset(); } inline static Service& get() noexcept { return *svc; } private: inline static std::shared_ptr<Service> svc = nullptr; }; /// Some Services struct ITimer { virtual void foo() = 0; }; struct QtTimer: public ITimer { virtual void foo() override { std::cout << "QtTimer::foo()\n"; } }; struct ILogger { virtual void log(const char*) const noexcept = 0; }; struct CoutLogger: public ILogger { virtual void log(const char* txt) const noexcept override { std::cout << "Log: " << txt << "\n"; } }; /// Usage struct AppRegistry { using Timer = Registry<ITimer>; using Logger = Registry<ILogger>; }; int main() { // some initialization part AppRegistry::Timer::assign<QtTimer>(); AppRegistry::Logger::assign<CoutLogger>(); // some other, usafe AppRegistry::Timer::get().foo(); AppRegistry::Logger::get().log("boo"); return 0; }