抄写了一个C++的孤子实现,代码来自与arcemu项目。
Singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include<assert.h>
#define initialiseSingleton( type )\
template <> type* Singleton<type>::mSingleton_=0
#define createSingleton( type )\
initialiseSingleton( type );\
type the##type
template<class T>
class Singleton
{
public:
Singleton(){
assert(this->mSingleton_==0);
this->mSingleton_=static_cast<T*>(this);
}
virtual ~Singleton()
{
this->mSingleton_=0;
}
static T &getSingleton(){
assert(mSingleton_);
return *mSingleton_;
}
static T* getSingletonptr()
{
assert(mSingleton_);
return mSingleton_;
}
protected:
static T *mSingleton_;
};
#endif // __SINGLETON_H__
test.cpp
#include<iostream>
#include<stdio.h>
#include<string.h>
#include"Singleton.h"
class TestSingleton:public Singleton<TestSingleton>
{
public:
TestSingleton(){}
~TestSingleton(){}
void print(char *s,int len)
{
printf("%s %d\n",s,len);
}
};
createSingleton(TestSingleton);
int main()
{
char s[]="hello fuck";
TestSingleton::getSingleton().print(s,strlen(s));
}
遇见错误的代码是这样的,提示A template declaration cannot appear at block scope。原因就是宏定义里面涉及到类的静态成员的初始化。You cannot define template inside a function, and main is a function。
int main()
{
char s[]="hello fuck";
createSingleton(TestSingleton);//wrong use
TestSingleton::getSingleton().print(s,strlen(s));
}