Adding arbitrary types to an object at runtime
In our application we have an object that receives attributes at runtime. For example, to add a float to the object:
my_object->f("volume") = 1.0f;
Retrieving the volume works the same way:
开发者_Python百科cout << my_object->f("volume") << endl;
Internally, this is represented by a map of strings to their respective type. Each type has its own access methods and map. It looks like this:
map<string, float> my_floats;
map<string, int> my_ints;
map<string, void *> my_void_pointers;
Oh, the dreaded void *
. Sometimes we need to add classes or functions to the object. Rather than have a separate map for every conceivable type, we settled on a void *
map. The problem we're having is with cleanup. Currently, we keep around a list of each type of these "dangling" objects that the void *
point to, and call a cleanup function on these separate lists when necessary.
I don't like having to use void *
and all the extra attention it requires for proper cleanup. Is there some better way to store arbitrary types in an object at runtime, accessible via a string map, and still benefit from automatic cleanup via destructor?
You are spoiled for choice here - boost::any or simply storing everything as std::string both come immediately to mind.
This post seems to be a good answer to your question.
Storing a list of arbitrary objects in C++
Rather than storing a map to so many values, it would be better to use a boost::variant. After all, judging by your interface, it would not be legal for me to assign both an int and a float to the same string.
std::map<std::string, boost::variant<float, int, std::string, ...>>;
精彩评论