C++ 如何在Meyers singleton模式中访问派生构造函数
我的代码:C++ 如何在Meyers singleton模式中访问派生构造函数,c++,design-patterns,singleton,C++,Design Patterns,Singleton,我的代码: template<class T> class Singleton { public: static T& instance() { static T obj; return obj; } protected: Singleton() { } Singleton(Singleton const& other); void operator=(Singleton const&
template<class T>
class Singleton {
public:
static T& instance() {
static T obj;
return obj;
}
protected:
Singleton() { }
Singleton(Singleton const& other);
void operator=(Singleton const& other);
};
class Derived : public Singleton<Derived> {
protected:
Derived() { }
};
void test() {
Derived::instance();
}
我该如何解决这个问题?可能使用friend
关键字?但那会有点尴尬
注意:我知道Meyers singleton的名字和想法,但我自己实现它的原因是我找不到我第一次读到它的地方。我认为它要么在“高效C++中”,要么在“更高效的C++中”,但我在那里找不到它。我在网上找到的例子没有使用CRTP泛化。使
单例实例函数成员成为派生的朋友:
struct Derived{
//...
friend Derived& Singleton<Derived>::instance();
};
struct派生{
//...
源于朋友的&Singleton::instance();
};
singleton模式后来被它自己的创建者放弃了。你可能应该避免使用它。迈尔斯不是作者之一。这确实不是最好的想法。这段5分钟的视频来自CppCon2016(),很有趣,很有教育意义!(名称空间是单例[可扩展的])甚至更简单:publicsingleton{friendclasssingleton;…
struct Derived{
//...
friend Derived& Singleton<Derived>::instance();
};