9

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!

4

1 回答 1

9

这应该是相当直截了当的。在心脏你应该有这样的事情:

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...>并且您需要传递谓词(作为练习留下)。Cons可能看起来像这样:

template <typename, typename> struct Cons;

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

的结果filter<Args...>::typestd::tuple<Brgs...>,其中Brgs...是一个包,只包含Args...谓词适用的那些类型。

于 2013-08-21T19:54:37.783 回答