简体   繁体   中英

Does Boost Variant provides a similar function as std's 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';
}

Although not exactly the same, you can use the pointer based get function:

boost::variant<int, std::string> v = "abc";

std::cout << std::boolalpha
          << "variant holds int? "
          << (boost::get<int>(&v) != nullptr) << '\n'
          << "variant holds string? "
          << (boost::get<std::string>(&v) != nullptr) << '\n';

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.

You can create a simple wrapper that will work just like the standard one. Use the fact that boost::get has multiple overloads and when passed a pointer, it will also return a (possibly null) pointer.

template <typename T, typename... Ts>
bool holds_alternative(const boost::variant<Ts...>& v) noexcept
{
    return boost::get<T>(&v) != nullptr;
}

It will be also picked up by ADL, so it doesn't matter much where you put it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM