我不会对OBJECT_DEF()使用hack
每个类都有一个唯一的名称(由编译器定义),可以通过type_info访问该名称
然后我会使用boost any对象将这些信息很好地存储在地图中。
我还没查过。
但现在,register可以用于任何类型。
#include <map>
#include <boost/any.hpp>
#include <typeinfo>
#include <string>
#include <iostream>
class Register
{
static std::map<std::string, boost::any> data;
public:
// If you just want to store pointers then:
// alter the input parameter to Set() to be T*
// alter the output of Get() to be T* and modify the any_cast.
//
// If you are just storing pointers I would also modify the map
// to be a boost::pointer_map so that ownership is transfered
// and memory is cleaned up.
template<typename T>
static void Set(T const& value)
{
data[std::string(typeid(T).name())] = boost::any(value);
}
template<typename T>
static T Get()
{
return boost::any_cast<T>(data[std::string(typeid(T).name())]);
}
};
std::map<std::string, boost::any> Register::data;
int main()
{
// Currently this line will leak as register does not take ownership.
Register::Set(new int(1));
// This line works fine.
Register::Set(int(5));
std::cout << *(Register::Get<int*>()) << "\n";
std::cout << Register::Get<int>() << "\n";
}