过滤参数包的类型 [英] Filter the types of a parameter pack

查看:63
本文介绍了过滤参数包的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以过滤传递给可变参数模板的类型(基于谓词模板)以生成另一个可变参数模板,其中包含满足谓词的类型:

I'd like to know if it's possible to filter the types passed to a variadic template (based on a predicate template) to produce another variadic template containing those types which satisfy the predicate:

/** Filter a parameter pack */    
template <template <class> class,
          template <class...> class,
          class...>
struct filter;
template <template <class> class Pred, template <class...> class Variadic>
struct filter<Pred, Variadic> : Variadic<>
{};
template <template <class> class Pred,
          template <class...> class Variadic,
          class T, class... Ts>
struct filter<Pred, Variadic, T, Ts...>
{
    // FIXME: this just stops at first T where Pred<T> is true
    using type = typename std::conditional<
        Pred<T>::value,
        Variadic<T, Ts...>,    // can't do: Variadic<T, filter<...>>
        filter<Pred, Variadic, Ts...> >::type;
};

如您所见,我还没有找到一种从其余过滤类型中提取"参数包的方法.

As you can see, I haven't found a way to "extract" the parameter pack from the rest of the filtered types.

提前谢谢!

推荐答案

那应该很简单.内心应该有这样的东西:

That should be fairly straight-forward. At the heart you should have something like this:

template <typename...> struct filter;

template <> struct filter<> { using type = std::tuple<>; };

template <typename Head, typename ...Tail>
struct filter<Head, Tail...>
{
    using type = typename std::conditional<Predicate<Head>::value,
                               typename Cons<Head, typename filter<Tail...>::type>::type,
                               typename filter<Tail...>::type
                          >::type;
};

您只需要 Cons< T,Tuple> ,这会将 T,std :: tuple< Args ...> 转换为 std :: tuple< T,Args ...> ,并且您需要沿途传递谓词(作为练习).缺点可能看起来像这样:

You just need Cons<T, Tuple>, which turns T, std::tuple<Args...> into std::tuple<T, Args...>, and you need to pass the predicate along (left as an exercise). Cons could look like this:

template <typename, typename> struct Cons;

template <typename  T, typename ...Args>
struct Cons<T, std::tuple<Args...>>
{
    using type = std::tuple<T, Args...>;
};

filter< Args ...> :: type 的结果将是 std :: tuple< Brgs ...> ,其中 Brgs... 是一个包,仅包含谓词所保存的 Args ... 中的那些类型.

The result of filter<Args...>::type would be std::tuple<Brgs...>, where Brgs... is a pack consisting of only those types in Args... for which the predicate holds.

这篇关于过滤参数包的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆