Skip to content

Instantly share code, notes, and snippets.

@sigman78
Created April 17, 2019 12:57
Show Gist options
  • Save sigman78/34b7e2ffa0024a0542d9e4197e797c89 to your computer and use it in GitHub Desktop.
Save sigman78/34b7e2ffa0024a0542d9e4197e797c89 to your computer and use it in GitHub Desktop.
Discoverable 'global vars'
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment