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

标签 c++ templates c++14

如何将 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>

live on coliru

我将如何传递整数序列?

最佳答案

您需要(部分)专门化 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");
}

DEMO

关于c++ - 将 std::integer_sequence 作为模板参数传递给元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31893102/

相关文章:

c++ - CvSVM(const CvSVM&)’是私有(private)的

android - 我可以在Android上安装Linux开发工具吗?

c++ - 根据模板参数添加成员函数和成员变量

c++ - 模板函数产生 undefined reference 错误

c++ - lambdas 和 std::function 的包装器

c++ - 是否有 C++11 到 C++03 的转换器?

可以实例化c++类模板,但具有相同模板参数的函数模板实例化失败

c++ - 合并排序实现未按预期工作

c++ - 具有 std::function 参数的不同重载与 bind 不明确(有时)

c++ - 如何根据C++版本选择函数实现