</pre><pre>
// singleton.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "singleton.h"
int _tmain(int argc, _TCHAR* argv[])
{
Msg::Instance().sayHello();
return 0;
}
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
template<class T>
class singleton
{
public:
static T& Instance()
{
if(!pInstance)
{
pInstance = new T;
}
return *pInstance;
}
private:
singleton();
static T* pInstance;
};
template<class T> T* singleton<T>::pInstance = NULL;
class msg{
public:
void sayHello(){std::cout<<"hello"<<std::endl;};
};
typedef singleton<msg> Msg;
#endif