jeudi 19 août 2021

Singleton CRTP with meyers singleton

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 ?

Aucun commentaire:

Enregistrer un commentaire