在运行时向对象添加任意类型
在我们的应用程序中,我们有一个在运行时接收属性的对象。例如,要向对象添加浮点:
my_object->f("volume") = 1.0f;
检索体积的工作方式相同:
cout << my_object->f("volume") << endl;
在内部,这由字符串到其各自类型的映射表示。每种类型都有自己的访问方法和映射。它看起来像这样:
map<string, float> my_floats;
map<string, int> my_ints;
map<string, void *> my_void_pointers;
哦,可怕的 void *
。有时我们需要向对象添加类或函数。我们没有为每种可能的类型使用单独的映射,而是选择了 void *
映射。我们遇到的问题是清理工作。目前,我们保留了 void * 指向的每种类型的“悬空”对象的列表,并在必要时对这些单独的列表调用清理函数。
我不喜欢使用 void *
以及正确清理所需的所有额外注意。是否有更好的方法可以在运行时在对象中存储任意类型,可以通过字符串映射进行访问,并且仍然可以通过析构函数从自动清理中受益?
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:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你会被这里的选择宠坏了 - boost::any 或简单地将所有内容存储为 std::string 都会立即浮现在脑海中。
You are spoiled for choice here - boost::any or simply storing everything as std::string both come immediately to mind.
这篇文章似乎很好地回答了你的问题。
用 C++ 存储任意对象列表
This post seems to be a good answer to your question.
Storing a list of arbitrary objects in C++
与其存储这么多值的映射,不如使用 boost::variant。毕竟,从你的界面来看,将 int 和 float 分配给同一个字符串对我来说是不合法的。
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.