#ifndef CTEMPLETESINGLETON_H_
#define CTEMPLETESINGLETON_H_
template<class T>
class CTempleteSingleton
{
public:
static T* Instance()
{
if(!pInstance_)
pInstance_=new T;
return pInstance_;
}
private:
CTempleteSingleton(){};
CTempleteSingleton(const CTempleteSingleton&);
CTempleteSingleton& operator=(const CTempleteSingleton&);
~CTempleteSingleton(){};
static T* pInstance_;
};
template<class T>
T* CTempleteSingleton<T>::pInstance_=0;
#endif
class A
{
int a;
};
int main()
{
A* p=CTempleteSingleton<A>::Instance();
return 0;
}
本文介绍了一种使用模板化方式实现的通用单例模式。该实现允许为任意类型创建单例实例,并确保线程安全。通过示例展示了如何为具体类(如“A”类)获取单例实例。

5286

被折叠的 条评论
为什么被折叠?



