反转C ++元组

时间:2014-08-04 12:47:08

标签: c++ c++11 tuples reverse

我想要反转C ++元组的内容。我正在尝试this answer中建议的以下代码:

template<typename T, size_t... I>
auto
reverse_impl(T&& t, redi::index_sequence<I...>)
-> std::tuple<typename std::tuple_element<sizeof...(I) - 1 - I, T>::type...>
{
    return std::make_tuple(std::get<sizeof...(I) - 1 - I>(std::forward<T>(t));
}

template<typename T>
auto
reverse(T&& t)
-> std::tuple<typename std::tuple_element<N - 1 - I, T>::type...>
{
    return reverse_impl(std::forward<T>(t),
                        redi::make_index_sequence<std::tuple_size<T>::value>());
}

但是我从g ++ 4.8.1获得了这些错误消息:

foo.cc: In function ‘std::tuple<typename std::tuple_element<((sizeof (I ...) - 1) - I), T>::type ...> reverse_impl(T&&, redi::index_sequence<I ...>)’:
foo.cc:12:76: error: parameter packs not expanded with ‘...’:
   return std::make_tuple(std::get<sizeof...(I) - 1 - I>(std::forward<T>(t)));
                                                                            ^
foo.cc:12:76: note:         ‘I’
foo.cc: At global scope:
foo.cc:18:43: error: ‘N’ was not declared in this scope
 -> std::tuple<typename std::tuple_element<N - 1 - I, T>::type...>
                                           ^
foo.cc:18:51: error: ‘I’ was not declared in this scope
 -> std::tuple<typename std::tuple_element<N - 1 - I, T>::type...>
                                                   ^
foo.cc:18:55: error: template argument 1 is invalid
 -> std::tuple<typename std::tuple_element<N - 1 - I, T>::type...>
                                                       ^
foo.cc:18:62: error: expected parameter pack before ‘...’
 -> std::tuple<typename std::tuple_element<N - 1 - I, T>::type...>
                                                              ^
foo.cc:18:65: error: template argument 1 is invalid
 -> std::tuple<typename std::tuple_element<N - 1 - I, T>::type...>
                                                                 ^

我不知道如何修复它。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

我认为您发布的代码与错误消息相符。要获得该错误,)之后应该有另一个std::forward<T>(t),但为了解决该错误,它应该是)...

但代码仍然是假的,第二个函数中的N是什么? (这显然是我的错,因为复制的答案也是我的!)

应该是:

template<typename T>
auto
reverse(T&& t)
-> decltype(reverse_impl(std::forward<T>(t),
                        redi::make_index_sequence<std::tuple_size<T>::value>()))

这仍然不起作用,因为当使用左值元组调用时,类型T被推断为std::tuple<...>&,您无法使用tuple_size或{ {1}}引用,因此您需要删除引用:

tuple_element