c++boost

Does Boost.Variant provide a similar function to std::holds_alternative?


I found this code on cppreference.com. I was wondering if Boost provides a similar function for its variant type. I found the Boost documentation really awful and can't find anything.

int main()
{
    std::variant<int, std::string> v = "abc";
    std::cout << std::boolalpha
              << "variant holds int? "
              << std::holds_alternative<int>(v) << '\n'
              << "variant holds string? "
              << std::holds_alternative<std::string>(v) << '\n';
}

Solution

  • No but, you can use the type() method:

    #include <iostream>
    #include <boost/variant.hpp>
    
    int main()
    {
        boost::variant<int, std::string> v = "abc";
        std::cout << std::boolalpha
                  << "variant holds int? "
                  << (v.type() == typeid(int)) << '\n'
                  << "variant holds string? "
                  << (v.type() == typeid(std::string)) << '\n';
    }
    

    But it will not protect you against having the same type twice (boost::variant<int, int, std::string>) as std::holds_alternative would do.