如何从元组C过滤重复类型

一个过滤器如何从元组中过滤重复类型?

例如:

using Tuple = std::tuple<int, double, int, double, std::string, std::string>
using FilteredTuple = without_duplicates<Tuple>;

在其中without_duplicates的实现方式是生成以下FilteredTuple类型:

std::tuple<int, double, std::string>

解决方法:

这项应有的工作:

template <class Haystack, class Needle>
struct contains;

template <class Car, class... Cdr, class Needle>
struct contains<std::tuple<Car, Cdr...>, Needle> : contains<std::tuple<Cdr...>, Needle>
{};

template <class... Cdr, class Needle>
struct contains<std::tuple<Needle, Cdr...>, Needle> : std::true_type
{};

template <class Needle>
struct contains<std::tuple<>, Needle> : std::false_type
{};



template <class Out, class In>
struct filter;

template <class... Out, class InCar, class... InCdr>
struct filter<std::tuple<Out...>, std::tuple<InCar, InCdr...>>
{
  using type = typename std::conditional<
    contains<std::tuple<Out...>, InCar>::value
    , typename filter<std::tuple<Out...>, std::tuple<InCdr...>>::type
    , typename filter<std::tuple<Out..., InCar>, std::tuple<InCdr...>>::type
  >::type;
};

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


template <class T>
using without_duplicates = typename filter<std::tuple<>, T>::type;

[Live example]

它通过迭代构造输出元组来工作.在添加每种类型之前,请检查(使用谓词包含)它是否已经在输出元组中.如果不是,则添加它(std :: conditional的“ else”分支),否则不添加它(std :: conditional的“ then”分支).

上一篇:python-将字符串的列转换为以pandas列出


下一篇:c-在模板化类的可变参数模板中包装每种类型