C++单例模板

时间:2022-06-06 06:22:14
#pragma once

namespace MyGame
{
    template<typename T>
    class Global
    {
    public:
        static void Create()
        {
            ASSERT(!s_instance);
            s_instance = new T;
        }

        static void Set(T* obj)
        {
            ASSERT(!s_instance);
            s_instance = obj;
        }

        static T& Get()
        {
            ASSERT(s_instance);
            return *s_instance;
        }

        static void Destroy()
        {
            ASSERT(s_instance);
            delete s_instance;
            s_instance = ;
        }
    private:
        Global();
        Global(Global&);
        Global& operator =(Global&);

        static T* s_instance;
    };

    template<typename T>
    T* Global<T>::s_instance = ;
}