jeudi 8 août 2019

Singleton get instance from constructor

I have a Singleton class. I'm trying to cutout the Get function when getting the Singleton instance. Is there anyway to do this.

template <typename T>
class SingletonPtr {
public:
    T* operator->() { return instance; }
    const T* operator->() const { return instance; }
    T& operator*() { return *instance; }
    const T& operator*() const { return *instance; }

    static T& Get() {
        std::lock_guard<std::mutex> myLock(_mutex);
        if (!instance)
            instance = new T();
        return *instance;
    }
private:
    static std::mutex _mutex;
    static T* instance;
};
template <typename T> T* SingletonPtr<T>::instance = nullptr;
template <typename T> std::mutex SingletonPtr<T>::_mutex;

class Log : public SingletonPtr<Log>{
public:
    int test(int size){
        return size * 2;
    }
};

i call it like this

Log::Get()->test(1);

I would like to call it something like this

Log()->test(1);
Log->test(1);

Aucun commentaire:

Enregistrer un commentaire