Boost Variant: how to get currently held type?

后端 未结 4 2104
感情败类
感情败类 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:11

    You can use the pointer version of boost::get. The tutorial has this example:

    void times_two( boost::variant< int, std::string > & operand )
    {
        if ( int* pi = boost::get( &operand ) )
            *pi *= 2;
        else if ( std::string* pstr = boost::get( &operand ) )
            *pstr += *pstr;
    }
    

    So you use it like you normally would use boost::get but pass a pointer to a variant instead, and the result is a pointer which is nullptr if that is not the type currently stored in the variant. It's not useful if that type appears more than once in the list of types in the variant, but that is not very common.

提交回复
热议问题