Storing a list of arbitrary objects in C++

前端 未结 13 2021
野趣味
野趣味 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

    While you cannot store primitive types in containers, you can create primitive type wrapper classes which will be similar to Java's autoboxed primitive types (in your example the primitive typed literals are actually being autoboxed); instances of which appear in C++ code (and can (almost) be used) just like primitive variables/data members.

    See Object Wrappers for the Built-In Types from Data Structures and Algorithms with Object-Oriented Design Patterns in C++.

    With the wrapped object you can use the c++ typeid() operator to compare the type. I am pretty sure the following comparison will work: if (typeid(o) == typeid(Int)) [where Int would be the wrapped class for the int primitive type, etc...] (otherwise simply add a function to your primitive wrappers that returns a typeid and thus: if (o.get_typeid() == typeid(Int)) ...

    That being said, with respect to your example, this has code smell to me. Unless this is the only place where you are checking the type of the object, I would be inclined to use polymorphism (especially if you have other methods/functions specific with respect to type). In this case I would use the primitive wrappers adding an interfaced class declaring the deferred method (for doing 'do stuff') that would be implemented by each of your wrapped primitive classes. With this you would be able to use your container iterator and eliminate your if statement (again, if you only have this one comparison of type, setting up the deferred method using polymorphism just for this would be overkill).

提交回复
热议问题