关于singleton模板错误,在线等待……
//Singleton.h
#ifndef __Singleton_H_
#define __Singleton_H_
#include <memory>
using namespace std;
namespace UsrLib
{
template <typename T>
class Singleton
{
public:
static T* getInstance();
virtual~Singleton(){}
protected:
Singleton(){}
private:
static std::auto_ptr <T> pSingleton;
Singleton(const Singleton&){}
Singleton& operator=(const Singleton&){}
};
};
#endif
//Singleton.cpp
#include "Singleton.h "
namespace UsrLib
{
template <typename T> std::auto_ptr <T> Singleton <T> ::pSingleton;
template <typename T> T* Singleton <T> ::getInstance()
{
if(pSingleton.get() == 0)
pSingleton.reset(new T);
return pSingleton.get();
}
};
声明了一个类:
//SingleModel.h
#ifndef _SingleModel_H__
#define _SingleModel_H__
#include "Singleton.h "
using namespace UsrLib;
class SingleModel:public Singleton <SingleModel>
{
public:
int i;
virtual ~SingleModel(void)
{
cout < < "destruct " < < endl;
}
void print()
{
cout < < "hello world " < < endl;
}
private:
friend class Singleton <SingleModel> ;
SingleModel():i(0)
{
cout < < "construct " < < endl;
}
};
#endif
在main里用SingleModel::getInstance()报错:
LNK2019: 无法解析的外部符号 "private: static class std::auto_ptr <class SingleModel> UsrLib::Singleton <class SingleModel> ::pSingleton " (?pSingleton@?$Singleton@VSingleModel@@@UsrLib@@0V?$auto_ptr@VSingleModel@@@std@@A),该符号在函数 "public: static class SingleModel * __cdecl UsrLib::Singleton <class SingleModel> ::getInstance(void) " (?getInstance@?$Singleton@VSingleModel@@@UsrLib@@SAPAVSingleModel@@XZ) 中被引用
不知道错误在哪里?
[解决办法]
google “模板分离编译模式”