将std :: integer_sequence作为模板参数传递给元函数

m.s*_*.s. 9 c++ templates c++14

如何std::integer_sequence将模板参数作为模板参数传递给元函数(即不是函数模板)?

给出例如以下用例(但不限于此):

我想使用整数序列N从参数包中删除最后的类型.我以为我可以使用selector来自这太问题,但我不整数序列传递给该元函数.

#include <tuple>
#include <utility>

template <typename T, std::size_t... Is>
struct selector
{
    using type = std::tuple<typename std::tuple_element<Is, T>::type...>;
};

template <std::size_t N, typename... Ts>
struct remove_last_n
{
    using Indices = std::make_index_sequence<sizeof...(Ts)-N>;  
    using type = typename selector<std::tuple<Ts...>, Indices>::type; // fails
};

int main()
{
    using X = remove_last_n<2, int, char, bool, int>::type;
    static_assert(std::is_same<X, std::tuple<int, char>>::value, "types do not match");
}
Run Code Online (Sandbox Code Playgroud)

编译器错误

main.cpp:15:55: error: template argument for non-type template parameter must be an expression

using type = typename selector<std::tuple<Ts...>, Indices>::type; // fails

                                                  ^~~~~~~

main.cpp:5:38: note: template parameter is declared here

template <typename T, std::size_t... Is>
Run Code Online (Sandbox Code Playgroud)

live on coliru

我如何传递整数序列?

Pio*_*cki 12

您需要(部分)专门化,selector以便从std::index_sequence以下方面推导出索引:

#include <tuple>
#include <utility>
#include <type_traits>

template <typename T, typename U>
struct selector;

template <typename T, std::size_t... Is>
struct selector<T, std::index_sequence<Is...>>
{
    using type = std::tuple<typename std::tuple_element<Is, T>::type...>;
};

template <std::size_t N, typename... Ts>
struct remove_last_n
{
    using Indices = std::make_index_sequence<sizeof...(Ts)-N>;  
    using type = typename selector<std::tuple<Ts...>, Indices>::type;
};

int main()
{
    using X = remove_last_n<2, int, char, bool, int>::type;
    static_assert(std::is_same<X, std::tuple<int, char>>::value, "types do not match");
}
Run Code Online (Sandbox Code Playgroud)

DEMO