【问题标题】:Singleton CRTP with meyers singleton带有迈耶斯单例的单例 CRTP
【发布时间】:2021-10-21 04:37:44
【问题描述】:

我正在尝试实现一个在内部使用 meyers 单例的单例模板:

#include <bits/stdc++.h>

template <typename T>
class Singleton {
public:
    static T& instance() {
       static T _instance; 
       return _instance;
    }
protected:
    Singleton() = default;
    ~Singleton() = default;
    Singleton(const Singleton & s) = delete;
    Singleton& operator=(const Singleton & s) = delete;
};


class Foo : Singleton<Foo> {
public:
    void print() {
       std::cout<<"from the foo singleton count : " <<count++<<std::endl; 
    }
private:
    int count = 0;

};

int main () {
   Singleton<Foo>::instance().print();
   Singleton<Foo>::instance().print();
   Singleton<Foo>::instance().print();
   return 0; 

它似乎工作:link

但现在我希望能够像这样使用它:

Foo::instance().print();

有什么办法吗?

【问题讨论】:

  • #include 从不使用它。 stackoverflow.com/questions/31816095/…
  • 我认为你需要 `class Foo : PUBLIC Singleton'
  • 顺便说一句,Foo 不是真正的单身人士。 Foo 默认可在任何范围内构造。

标签: c++ templates design-patterns singleton crtp


【解决方案1】:

您正在使用带有class Foo : Singleton&lt;Foo&gt; 的私有继承,这意味着对于外界来说,Foo 不是Singleton&lt;Foo&gt; 并且它没有instance 函数。你可以添加

using Singleton<Foo>::instance;

Foo的公共部分。这会将instance 函数导入Foo 的公共空间并允许

Foo::instance().print();

编译。

【讨论】:

    【解决方案2】:

    您应该阅读尝试调用Foo::instance().print() 导致的错误消息,因为它告诉您出了什么问题:

    <source>:30:17: error: 'static T& Singleton<T>::instance() [with T = Foo]' is inaccessible within this context
       30 |    Foo::instance().print();
          |    ~~~~~~~~~~~~~^~
    

    Singleton&lt;T&gt;::instance() 无法通过Foo::instance() 访问,因为Foo 是私有继承的。让Foo 公开继承,它可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      相关资源
      最近更新 更多