Is there an elegant way to represent a map containing different types in C++?

前端 未结 4 1102
小蘑菇
小蘑菇 2021-01-15 13:16

I\'m building a class which I want to configure using various parameters which may one of: int, double and string (or const char

4条回答
  •  青春惊慌失措
    2021-01-15 13:48

    The sensible thing to do would be to use Boost.Variant, which is developed by expert C++ programmers and honed and tested by hundreds of projects.

    But if that is not an option for you, I see the following alternatives:

    1. Reimplement Boost.Variant yourself. It will be a wonderful learning excercise, but it will take a lot of time to get right (and then more lots of time to fix all the bugs).

    2. Resign on time efficiency, store all the types in a std::string, and convert them in getters (originally suggested in a comment by @Galik).

    3. Resign on memory efficiency and store all three types in your class.

    4. If you have aversion against Boost specifically, use a different library which provides a variant type (like Qt's QVariant).

提交回复
热议问题