Storing a list of arbitrary objects in C++

前端 未结 13 2018
野趣味
野趣味 2021-02-06 08:29

In Java, you can have a List of Objects. You can add objects of multiple types, then retrieve them, check their type, and perform the appropriate action for that type.
For e

13条回答
  •  走了就别回头了
    2021-02-06 09:17

    How often is that sort of thing actually useful? I've been programming in C++ for quite a few years, on different projects, and have never actually wanted a heterogenous container. It may be common in Java for some reason (I have much less Java experience), but for any given use of it in a Java project there might be a way to do something different that will work better in C++.

    C++ has a heavier emphasis on type safety than Java, and this is very type-unsafe.

    That said, if the objects have nothing in common, why are you storing them together?

    If they do have things in common, you can make a class for them to inherit from; alternately, use boost::any. If they inherit, have virtual functions to call, or use dynamic_cast<> if you really have to.

提交回复
热议问题