Skip to content

Instantly share code, notes, and snippets.

@sigman78
Created April 17, 2019 12:57
Show Gist options
  • Select an option

  • Save sigman78/34b7e2ffa0024a0542d9e4197e797c89 to your computer and use it in GitHub Desktop.

Select an option

Save sigman78/34b7e2ffa0024a0542d9e4197e797c89 to your computer and use it in GitHub Desktop.

Revisions

  1. sigman78 created this gist Apr 17, 2019.
    73 changes: 73 additions & 0 deletions registry.cpp
    Original 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;
    }