Boost Variant: how to get currently held type?

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

    You can use the following that both result in std::type_info objects:

    • the type() member function of boost::variant,
    • the C++ operator typeid() that can be applied to any type or typed expression,

    together with the member function std::type_info::operator==, to check which type the boost::variant is currently storing. For example,

    boost::variant container;
    container = "Hello world";
    
    if (container.type() == typeid(std::string)) {
        std::cout << "Found a string: " << boost::get(container);
    }
    else if (container.type() == typeid(int)) {
        std::cout << "Found an int: " << boost::get(container);
    }
    

提交回复
热议问题