Get element by index from boost :: variant using std :: variant as possible

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

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

+5
source share
1 answer

This does not seem to be included in boost.

However, using this answer , we can simply play our part:

 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); } 

Watch live .

Cursor overloads, of course, can be added in the same way, if necessary.

+5
source

Source: https://habr.com/ru/post/1270857/


All Articles