Construct a std::variant out of a boost::variant

139 Views Asked by At

I'm trying to construct a std::variant out of a boost::variant. In practice, I'm trying to define a function with the following signature:

template <typename... Types>
std::variant<Types...>
boostvar2stdvar(boost::variant<Types...> input);

I've seen the answer to this question, but in that case it's converting a tuple to a std::variant, not a boost::variant. I need my function to take a boost::variant directly. Is there an easy way to do that?

1

There are 1 best solutions below

0
sehe On BEST ANSWER

As others have pointed out, you can visit all elements types and return the desired variant from there:

template <typename... Types> auto b2std(boost::variant<Types...> const& input) {
    return boost::apply_visitor(
        [](auto const& v) -> std::variant<Types...> { return v; }, input);
}

When used like this

auto x = b2std(boost::variant<int, std::string, double>{"hello world"});

Then type of x matches the expected:

static_assert(
    std::is_same_v<std::variant<int, std::string, double>, decltype(x)>);

Live

See it Live On Coliru

#include <boost/variant.hpp>
#include <variant>
#include <iostream>

template <typename... Types> auto b2std(boost::variant<Types...> const& input) {
    return boost::apply_visitor(
        [](auto const& v) -> std::variant<Types...> { return v; }, input);
}

int main() {
    auto x = b2std(boost::variant<int, std::string, double>{"hello world"});
    static_assert(
        std::is_same_v<std::variant<int, std::string, double>, decltype(x)>);
}