1

i am tring to implement a Singleton template that using meyers singleton inside:

#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; 

and it seems to work : link

but now i want to be able to using it like this :

Foo::instance().print();

is there any way to do it ?

wangzj
  • 55
  • 7

2 Answers2

3

You are using private inheritance with class Foo : Singleton<Foo> which means to the outside world, Foo is not a Singleton<Foo> and it doesn't have a instance function. You can add

using Singleton<Foo>::instance;

To the public section of Foo. That will import the instance function into the public space of Foo and allow

Foo::instance().print();

to compile.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

You should read the error message that results from trying to call Foo::instance().print() because it tells you whats wrong:

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

Singleton<T>::instance() is inaccessible via Foo::instance() because Foo inherits privately. Make Foo inherit publicly and it works.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185