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

1

6

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.

Leyva answered 14/8, 2017 at 14:28 Comment(4)
Looks like you can't.Almetaalmighty
@BaummitAugen and is there a way to hack it? perhaps with some mpl shenanigans?Leyva
Most likely yes. What standard?Almetaalmighty
@BaummitAugen I use the (almost) latest of compilers - only emscripten is making me lagg behind - it's version of libcxx doesn't have <variant> yet... so C++14 (also latest boost)Leyva
A
7

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.

Almetaalmighty answered 14/8, 2017 at 14:43 Comment(4)
yeah my bad - the const-ness got propagated properly by just using auto. Thanks for the answer! IMHO this needs to be added to boost::variant...Leyva
@Leyva Never tried contributing, but I guess you could submit a patch. Don't see why they would be against having it. (Not sure what standard they use though, in C++11, this already gets slightly more ugly and I'm not sure how to do it in C++03.)Almetaalmighty
@Leyva it is my firm view that access by index, when you have access by type available, is an utter anti-pattern.Eulaeulachon
@RichardHodges, in a dynamic environment, the index() (which() in boost) and get() are very useful.Mardellmarden

© 2022 - 2024 — McMap. All rights reserved.