一种单例的实现方法

来源:互联网 发布:如何用excel做数据库 编辑:程序博客网 时间:2024/05/17 21:42
/*用法:class A:public Singleton<A>{};在cpp文件中:template<> A* Singleton<A>::singleton_ = 0;*/#ifndef SINGLETON_H#define SINGLETON_H#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000// common include#include "common/platform.h"#include <stdio.h>#include <stdlib.h>#include <assert.h>// windows include#if PLATFORM == PLATFORM_WIN32#else// linux include#include <errno.h>#endifnamespace Core{template <typename T> class Singleton{protected:static T* singleton_;public:Singleton(void){assert(!singleton_);#if defined(_MSC_VER) && _MSC_VER < 1200 int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;singleton_ = (T*)((int)this + offset);#elsesingleton_ = static_cast< T* >(this);#endif}~Singleton(void){  assert(singleton_);  singleton_ = 0; }static T& getSingleton(void) { assert(singleton_);  return (*singleton_); }static T* getSingletonPtr(void){ return singleton_; }};#define SINGLETON_INIT( TYPE )\template <> TYPE * Singleton< TYPE >::singleton_ = 0;\}#endif // SINGLETON_H

0 0
原创粉丝点击