【发布时间】:2020-07-12 17:29:15
【问题描述】:
我正在尝试 C++ 类型列表。下面是一个类型列表过滤函数的简单实现。除了 gcc 和 clang 中的编译时间超出 18 个元素之外,它似乎有效。我想知道我可以做哪些改进来实现这一点。
#include <type_traits>
// a type list
template <class... T> struct tl ;
// helper filter for type list
template <class IN_TL, class OUT_TL, template <typename> class P>
struct filter_tl_impl;
// Base case
template <class... Ts, template <typename> class P>
// If the input list is empty we are done
struct filter_tl_impl<tl<>, tl<Ts...>, P> {
using type = tl<Ts...>;
};
// Normal case
template <class Head, class... Tail, class... Ts2, template <typename> class P>
struct filter_tl_impl<tl<Head, Tail...>, tl<Ts2...>, P> {
using type = typename std::conditional<
// Does the predicate hold on the head of the input list?
P<Head>::value,
// The head of the input list matches our predictate, copy it
typename filter_tl_impl<tl<Tail...>, tl<Ts2..., Head>, P>::type,
// The head of the input list does not match our predicate, skip
// it
typename filter_tl_impl<tl<Tail...>, tl<Ts2...>, P>::type>::type;
};
template <class TL, template <typename> class P> struct filter_tl {
using type = typename filter_tl_impl<TL, tl<>, P>::type;
};
// Test code
using MyTypes = tl<
char*, bool, char, int, long, void,
char*, bool, char, int, long, void,
char*, bool, char, int, long, void
>;
using MyNumericTypes = filter_tl<MyTypes, std::is_arithmetic>::type;
static_assert(std::is_same < MyNumericTypes,
tl<
bool,char,int,long,
bool,char,int,long,
bool,char,int,long
>> :: value);
int main(int, char **) {}
【问题讨论】:
-
很抱歉,如果您有超过 18 个元素,您将创建 60 多个不同的类,而不是原始数据类型,请注意,类,是什么让您认为运行该程序的时间会很快?
-
@YunfeiChen 你住在 1957 年吗?
-
嗯,你所做的类似于创建 60 个不同的文件并定义 60 个不同的头文件并制作它们......试试看,你会得到一个丑陋的目录,它需要永远运行...... ...从透视角度来看....
-
那不是云飞。一个文件中的 60 个简单类根本不需要时间来编译。正如下面的 Jarod42 和 HTNW 讨论的那样,我的递归存在问题,两个分支都被占用,导致 ~2^18 类。
标签: c++ variadic-templates template-meta-programming