How to extract a subset of a tuple in a new tuple?

I have a class that contains a tuple of variable types, such as:

template<class... Ts> struct Tester { std::tuple<Ts...> t; template<class... T2s> std::tuple<T2s...> Get() { ??? } }; 

Instance example Tester<int, float, char>

I want my Get function to return only a subset of the inner tuple. For example, tester.Get<int, char> will return the value std::tuple<int, char> , the values โ€‹โ€‹of which will be copied from the corresponding elements of the internal tuple.

It can be assumed that each type appears at most once in a tuple and that Get will be called only with reasonable template parameters that are in the tuple.

+6
source share
1 answer

In fact, it is easier than you think. std::get takes the type as an alternative to the index of the set member (starting with C ++ 14) and returns the first type of correspondence from the tuple:

 #include <tuple> #include <iostream> #include <type_traits> template<class... Ts> struct Tester { std::tuple<Ts...> t; template<class... T2s> std::tuple<T2s...> Get() { return std::tuple<T2s...> {std::get<T2s>(t)...}; } }; int main() { Tester<int, char, float> t; tt=std::make_tuple(0,1,2); auto result=t.Get<int, float>(); std::cout << std::is_same<decltype(result), std::tuple<int, float>>::value << std::endl; int &i=std::get<0>(result); float &f=std::get<1>(result); std::cout << i << " " << f << std::endl; return 0; } 

The output checked with gcc 6.3.1:

 1 0 2 
+8
source

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


All Articles