Boost Variant: how to get currently held type?

后端 未结 4 2127
感情败类
感情败类 2020-12-29 01:27

As I understood all types of boost.variant are parsed into real types (meaning as if boost variant a; a=\"bla-bla\" would after compilation t

4条回答
  •  感动是毒
    2020-12-29 02:21

    v.which() will return the 0-based index of the type of the object currently held.

    When you are retrieving the object your code must use a static type (in order to satisfy the get function template) to refer to an (effectively) dynamically typed object.

    You need to either test for the type (using which() or type()) and branch accordingly or use a static visitor. No matter which way you choose, you have to explicitly state the static type that you want to retrieve and it has to match the dynamic type or an exception will be thrown.

    One way around this problem is instead of using a variant type directly, use a class which contains a variant type internally and then defines any implicit conversion operators necessary to use the object with minimum fuss.

    I have a project called Dynamic C++ which uses this technique.

提交回复
热议问题