Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

template<class... Ts>
struct Tester
{
    std::tuple<Ts...> t;

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

An example instance is 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 a std::tuple<int, char> whose values are copied from the appropriate members of the inner tuple.

You can assume that each type appears a maximum of once in a tuple and that Get will only be called with sensible template parameters that are in the tuple.

like image 232
Neil Kirk Avatar asked Jan 02 '17 03:01

Neil Kirk


1 Answers

Actually, this is easier than you think. std::get takes a type, as an alternative to the tuple member index (since C++14), and returns the first matching type 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;

    t.t=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;
}

Output, tested with gcc 6.3.1:

1
0 2
like image 159
Sam Varshavchik Avatar answered Sep 21 '22 13:09

Sam Varshavchik