Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get item by index from boost::variant like it's possible with std::variant

With std::variant<int, bool> I can call std::get<0>(var) to get the value in the variant as it's first type - int.

How can I do this with boost::variant? boost::get<> seems to support only getting by type and not by index and I find the documentation very difficult to understand.

like image 342
onqtam Avatar asked Aug 14 '17 14:08

onqtam


1 Answers

This appears to be not included in boost.

However, with the help of this answer, we can simply role our own:

template<int N, typename... Ts> using NthTypeOf =
        typename std::tuple_element<N, std::tuple<Ts...>>::type;

template<int N, typename... Ts>
auto &get(boost::variant<Ts...> &v) {
    using target = NthTypeOf<N, Ts...>;
    return boost::get<target>(v);
}

template<int N, typename... Ts>
auto &get(const boost::variant<Ts...> &v) {
    using target = NthTypeOf<N, Ts...>;
    return boost::get<target>(v);
}

int main () {
    boost::variant<int, double> v = 3.2;
    std::cout << get<1>(v);
}

See it live.

The pointer overloads can of course be added analogously if desired.

like image 125
Baum mit Augen Avatar answered Nov 15 '22 06:11

Baum mit Augen