Template singleton base class in shared object

前端 未结 1 1621
长发绾君心
长发绾君心 2020-12-22 03:30

I\'m currently porting my project from Windows to Linux.

The project consists of a \'main\' shared library, several plugins (also shared libraries) and a launcher ap

相关标签:
1条回答
  • 2020-12-22 03:48

    IMHO the closest thing you can get that suffices your requirements is something using the following pattern:

    #include <iostream>
    
    template<class Derived>
    class Singleton {
    public:
        static Derived& instance() {
            static Derived theInstance;
            return theInstance;
        }
    
    protected:
        Singleton() {}
    
    private:
        Singleton(const Singleton<Derived>&);
        Singleton<Derived>& operator=(const Singleton<Derived>&);
    };
    

    class ASingleton : public Singleton<ASingleton> {
    public:
        void foo() { std::cout << "foo() called ..." << std::endl; }
    };
    

    int main() {
        ASingleton& a = ASingleton::instance();
        a.foo();
        return 0;
    }
    

    Whatever you want to be accessible through an interface might be injected using multiple inheritance. Though the benefit of using a Singleton<Derived> base class is a bit questionable, it just provides that narrow instance() implementation.

    0 讨论(0)
提交回复
热议问题