Convert tuple to pair

Have educational task: write template function, which takes arbitrary std::tuple and 2 indexes inside and returns std::pair, containing elements of given std::tuple with correspondent indexes.

Example:

auto t = std::make_tuple(0, 3.5, "Hello");
std::pair<double, char const *> p = to_pair<1,2>(t); 
// p contains 3.5 and "Hello"

Written something like this:

template<int I, int J>
auto to_pair(std::tuple t) -> decltype(std::make_pair(std::get<I>(t), std::get<J>(t))) {
  return std::make_pair(std::get<I>(t), std::get<J>(t));
}

However got an error:

r: missing template arguments before ‘t’
auto to_pair(std::tuple t) -> decltype(std::make_pair(get<I>t, get<J>t))
                        ^

What I'm doing wrong and what is correct syntax here? Thanks!

1 answer

  • answered 2017-11-12 19:48 Darhuuk

    std::tuple is a template class, so there's no std::tuple, only std::tuple<T, ...>. In your case, the type of t is std::tuple<int, double, char const *>.

    Also, you're calling std::get without an argument (there's missing braces).

    You're almost there, the function should be something along the lines of:

    template<int I, int J, class... T>
    auto to_pair(std::tuple<T...> t)
        -> decltype(std::make_pair(std::get<I>(t), std::get<J>(t))) {
      return std::make_pair(std::get<I>(t), std::get<J>(t));
    }