Storing a list of arbitrary objects in C++

前端 未结 13 2238
野趣味
野趣味 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 08:59

    Beside the fact, as most have pointed out, you can't do that, or more importantly, more than likely, you really don't want to.

    Let's dismiss your example, and consider something closer to a real-life example. Specifically, some code I saw in a real open-source project. It attempted to emulate a cpu in a character array. Hence it would put into the array a one byte "op code", followed by 0, 1 or 2 bytes which could be a character, an integer, or a pointer to a string, based on the op code. To handle that, it involved a lot of bit-fiddling.

    My simple solution: 4 separate stacks<>s: One for the "opcode" enum and one each for chars, ints and string. Take the next off the opcode stack, and the would take you which of the other three to get the operand.

    There's a very good chance your actual problem can be handled in a similar way.

提交回复
热议问题