How can I store objects of differing types in a C++ container?

前端 未结 8 1627
一个人的身影
一个人的身影 2020-11-27 16:26

Is there a C++ container that I could use or build that can contain, say, int and string and double types? The problem I\'m facing is

8条回答
  •  余生分开走
    2020-11-27 17:12

    The simplest method is of course to define a struct or class that has members of each of the types you wish to store. Josh's answer suggests Boost.Any, which will hold pretty much anything. If you want to restrict values to only those of types int, double, and std::string, then the better choice would be Boost.Variant.

    If you simply don't want to use Boost, then I suggest you get over your hang-ups and use it anyway. "Not Invented Here" is a self-destructive policy. But if you can't use Boost, then you can write your own variant class instead. Andrei Alexandrescu wrote a three-part series on that (part 1, part 2, part 3) a few years ago, and its design inspired the one Boost uses.

提交回复
热议问题