简体   繁体   English

过滤参数包的类型

[英]Filter the types of a parameter pack

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. 如您所见,我还没有找到一种方法从其余的过滤类型中“提取”参数包。

Thanks in advance! 提前致谢!

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;
};

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<T, Tuple> ,它将T, std::tuple<Args...>转换为std::tuple<T, Args...> ,你需要传递谓词(左边作为行使)。 Cons could look like this: Cons可能如下:

template <typename, typename> struct Cons;

template <typename  T, typename ...Args>
struct Cons<T, std::tuple<Args...>>
{
    using type = std::tuple<T, 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. filter<Args...>::type将是std::tuple<Brgs...> ,其中Brgs...是一个包,只包含Args...那些类型Args...谓词所包含的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM