Union vs. static_cast(void*)

99封情书 提交于 2019-11-29 16:18:16

Consider boost::any or boost::variant if you want to store objects of heterogeneous types.

And before deciding which one to use, have a look at the comparison:

Hopefully, it will help you to make the correct decision. Choose one, and any of the container from the standard library to store the objects, std::vector<boost::any>, std::vector<boost::variant>, or any other.

boost::variant.

Basically, it is a type-safe union, and in this case, it seems like unions are by far the most appropriate answer. A void* could be used, but that would mean dynamic allocation, and you would have to maintain the Types enum, and the table for casting.

Memory constraints could make void* an acceptable choice, but it's not the 'neat' answer, and I wouldn't go for it until both boost::variant and just a plain union have shown to be unacceptable.

If your classes have enough in common to be put in the same container give them a base class with a virtual destructor, and possibly a virtual member function to retrieve your type code, even though at that point not only dynamic_cast would be more appropriate, but it could be reasonable to explore whether your classes don't have enough in common to provide them with a more complete common interface.

Otherwise consider providing a custom container class with appropriately typed data members to hold instances of all the different classes you need to put into it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!