如何将 std::integer_sequence
作为模板参数传递给元函数(即不是函数模板)?
给出例如以下用例(但不限于此):
我想使用整数序列从参数包中删除最后的 N
类型。我想我可以使用 this SO question 中的 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");
}
编译错误
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>
我将如何传递整数序列?
最佳答案
您需要(部分)专门化 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");
}
关于c++ - 将 std::integer_sequence 作为模板参数传递给元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31893102/