单例类模板程序
Singleton.h
#ifndef _SINGLETLON_H_ #define __SINGLETLON_H_ template <typename T> class singletlon { static T* Instance; public: static T* Get_Instance(); }; template <typename T> T* singletlon<T>:: Instance = NULL; template <typename T> T* singletlon<T>::Get_Instance() { if (Instance == NULL) { Instance = new T(); } return Instance; } #endif
main.cpp
#include <iostream> #include <string> #include "Singletlon.h" using namespace std; class SObject { friend class singletlon<SObject>; SObject() { } SObject(const SObject& obj); SObject& operator = (const SObject& obj); public: void print(); }; void SObject::print() { cout << "this=" << this << endl; } int main() { SObject* s1 = singletlon<SObject>:: Get_Instance(); SObject* s2 = singletlon<SObject>::Get_Instance(); SObject* s3 = singletlon<SObject>::Get_Instance(); s1->print(); s2->print(); s2->print(); }
来源:https://www.cnblogs.com/chengeputongren/p/12289239.html