首页 > 解决方案 > C++ typelist 制作子列表

问题描述

假设我有一个类型

template<typename ...Ts>
struct typelist {};

我需要从此列表中获取子列表:

template<int startInclusive, int stopExclusive, typename ...Ts>
struct sublist {
    using type = ?; //
};

例如

sublist<1, 3, int, float, double, char>::type == typelist<float, double>

start = 0我有一个有效的尾部实现时:

template<typename ...Ts>
struct typelist {};

template<int N, typename T, typename ...Ts>
struct tail {
    using type = typename tail<N - 1, Ts...>::type;
};

template<typename T, typename ...Ts>
struct tail<0, T, Ts...> {
    using type = typelist<T, Ts...>;
};

using T = tail<1, int, double>::type;

#include <typeinfo>
#include <cstdio>

int main() {
   ::printf("%s\n", typeid(T).name());
}

但是,我无法得到任何工作start > 0

标签: c++variadic-templatestypelist

解决方案


像往常一样,std::index_sequence这里有帮助:

template <std::size_t Offset, typename Seq, typename Tuple> struct sublist_impl;

template <std::size_t Offset, std::size_t ... Is, typename Tuple>
struct sublist_impl<Offset, std::index_sequence<Is...>, Tuple>
{
    using type = std::tuple<std::tuple_element_t<Offset + Is, Tuple>...>;
};

template<std::size_t startInclusive, std::size_t stopExclusive, typename ...Ts>
using sublist = typename sublist_impl<startInclusive,
                                 std::make_index_sequence<stopExclusive - startInclusive>,
                                 std::tuple<Ts...>>::type;

演示


推荐阅读