Template singleton base class in shared object

柔情痞子 提交于 2019-11-29 17:16:46

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!