如何通过类型派生过滤可变参数模板包?

时间:2015-11-05 11:21:39

标签: c++ templates c++11 variadic-templates

我有一个模板类接收多个类型,每个类型接收的是两个选项之一的子类。 我想根据父类识别它们来不同地扩展它们。这相当于对可变参数模板参数实现“过滤”。

例如:

class A{};
class B{};

template<class... C>
struct F{
     std::tuple<types_derived_by<A, C>...> fn(types_subclassing<B, C>...){}
};

types_derived_by模板函数应该生成一个可变参数模板包,其中包含从A或B派生的所有C类型。

例如:

struct DA : public A{};
struct DB : public B{};
int main(){
    F<DA, DB> f;
    //f has a member function: DA fn(DB);

}

我正在使用C ++ 11,但如果有必要,我可以转到c ++ 14。

2 个答案:

答案 0 :(得分:4)

您可以执行以下操作:

template <template <typename> class Pred, typename TUPLE, typename Res = std::tuple<>>
struct Filter;

template <template <typename> class Pred, typename Res> 
struct Filter<Pred, std::tuple<>, Res>
{
    using type = Res;
};

template <template <typename> class Pred, typename T, typename ... Ts, typename ... TRes> 
struct Filter<Pred, std::tuple<T, Ts...>, std::tuple<TRes...>> :
    Filter<Pred,
           std::tuple<Ts...>,
           std::conditional_t<Pred<T>::value,
                              std::tuple<TRes..., T>,
                              std::tuple<TRes...>>>
{
};

然后:

class A {};
template <typename T>
using is_base_of_A = std::is_base_of<A, T>;

class B {};
struct DA : public A{};
struct DB : public B{};
struct DA1 : public A{};

static_assert(std::is_same<std::tuple<DA, DA1>,
                           Filter<is_base_of_A, std::tuple<DA, DB, DA1>>::type>::value,
              "unexpected");

Demo

答案 1 :(得分:0)

如果您不介意使用元组作为返回值和参数,这可能是您的解决方案:

template <typename Base, typename...T>
struct base_filter;

template <typename Base>
struct base_filter<Base>
{
    using type = std::tuple<>;
};

template <typename Base, typename T1>
struct base_filter<Base, T1>
{
    using type = typename std::conditional_t<std::is_base_of<Base, T1>::value, std::tuple<T1>, std::tuple<>>;
};

template <typename Base, typename T1, typename...T>
struct base_filter<Base, T1, T...>
{
    using type = decltype(std::tuple_cat(base_filter<Base, T1>::type(), base_filter<Base, T...>::type()));
};


//###########################################################

class A {};
class B {};


template<class...C>
struct F {
    typename base_filter<A, C...>::type fn(typename base_filter<B, C...>::type){}
};

struct DA : public A {};
struct DB : public B {};
struct DA1 : public A {};
struct DA2 : public A {};
struct DB1 : public B {};
struct DB2 : public B {};


int main() {
    std::tuple<DB> b;
    F<DA, DB> f1;
    std::tuple<DA> a = f1.fn(b);

    std::tuple<DB1, DB2> bb;
    F<DB1, DA1, DB2, DA2> f2;
    std::tuple<DA1, DA2> aa = f2.fn(bb);
}