分类: C/C++
2008-05-25 22:15:29
突发奇想写了这个非常简单,但是很有用的东西:
需要 boost 库支持
文件名: Runtimeclass.hpp
#include
#include
#include
// Write by Jadedrip (Jadedrip@gmail.com)
#ifndef _TSTRDEFINED
#define _TSTRDEFINED
#ifdef _UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif
#endif
class RuntimeClassFactory
{
private:
typedef boost::function RUNTIME_CREATE_REF;
protected:
typedef std::map< tstring, RUNTIME_CREATE_REF > class_map;
static class_map& cmap(){
static class_map m_map;
return m_map;
}
public:
static void register_class( tstring name, RUNTIME_CREATE_REF p ){
(cmap())[name]=p;
}
static void* create( tstring name ){
if( cmap().find( name )!=cmap().end() )
return (cmap()[name])();
else
return NULL;
}
};
template
struct ClassObject
{
ClassObject(const tstring class_name){ RuntimeClassFactory::register_class( class_name, &ClassObject::create_object ); }
static void* create_object(){ return new T; }
};
#define REGISTER_CLASS(X) ClassObject __class_help_##X(_T(#X));
#define REGISTER_CLASS_BY_NAME(X,CLASSNAME) ClassObject __class_help_##X(_T(CLASSNAME));
class A{
...
};
REGISTER_CLASS(A)
void main()
{
tstring class_name=_T("A");
A* a=(A*)RuntimeClassFactory::create(class_name);
}