gpt4 book ai didi

c++ - 使用简单类型列表实现的指数编译时间。为什么?

转载 作者:行者123 更新时间:2023-12-01 13:00:02 25 4
gpt4 key购买 nike

我正在尝试使用 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 **) {}

最佳答案

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;
因为 ::type 实例化双方.
您可能会在 std::conditional 之后延迟中间实例化:
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 predicate, copy it
filter_tl_impl<tl<Tail...>, tl<Ts2..., Head>, P>,
// The head of the input list does not match our predicate, skip
// it
filter_tl_impl<tl<Tail...>, tl<Ts2...>, P>>::type::type;
这导致实例化的线性数量而不是指数。

关于c++ - 使用简单类型列表实现的指数编译时间。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62864301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com