检查一组类型是否为另一组的子集 [英] Check if one set of types is a subset of the other

查看:87
本文介绍了检查一组类型是否为另一组的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查一个参数包(解释为一组)是否是另一个参数包的子集?

How can one check if one parameter pack (interpreted as a set) is a subset of another one?

到目前为止,我只有框架(使用std: :tuple),但无功能。

So far I only have the frame (using std::tuple), but no functionality.

#include <tuple>
#include <type_traits>

template <typename, typename>
struct is_subset_of : std::false_type
{
};

template <typename ... Types1, typename ... Types2>
struct is_subset_of<std::tuple<Types1...>, std::tuple<Types2...>>
    : std::true_type
{
    // Should only be true_type if Types1 is a subset of Types2
};

int main() {
    using t1 = std::tuple<int, double>;
    using t2 = std::tuple<double, int>;
    using t3 = std::tuple<int, double, char>;

    static_assert(is_subset_of<t1, t1>::value, "err");
    static_assert(is_subset_of<t1, t2>::value, "err");
    static_assert(is_subset_of<t2, t1>::value, "err");
    static_assert(is_subset_of<t2, t3>::value, "err");
    static_assert(!is_subset_of<t3, t2>::value, "err");
}

每个类型不允许在一个集合中多次出现。

Every type is not allowed to occur more than once in a set.

如果该解决方案适用于C ++ 11,那就太好了。

It would be nice if the solution works with C++11.

推荐答案

如果可以使用C ++ 17功能,我强烈建议使用 Piotr Skotnicki的解决方案

If you can use C++17 features, I highly recommend using Piotr Skotnicki's solution!

我前一段时间必须实现此功能。我只是要复制粘贴当时我想出的代码。

I had to implement this functionality a while ago. I am just going to copy-paste the code I came up with at that point.

我并不是说这是实现这种方法的最好或最优雅的方法检查!我没有过多地考虑边缘情况。您可能需要修改代码以满足您的要求。

I am not claiming that this is the best or most elegant way to implement this kind of check! I did not bother thinking about the edge cases too much; you may need to adapt the code to fit your requirements.

要澄清: ContainsTypes< Lhs,Rhs> 检查如果 Rhs Lhs 的子集。

To clarify: ContainsTypes<Lhs, Rhs> checks if Rhs is a subset of Lhs.

  template <typename Tuple, typename T>
  struct ContainsType;

  template <typename T, typename U, typename... Ts>
  struct ContainsType<std::tuple<T, Ts...>, U>
  {
      static const bool VALUE = ContainsType<std::tuple<Ts...>, U>::VALUE;
  };

  template <typename T, typename... Ts>
  struct ContainsType<std::tuple<T, Ts...>, T>
  {
      static const bool VALUE = true;
  };

  template <typename T>
  struct ContainsType<std::tuple<>, T>
  {
      static const bool VALUE = false;
  };

  // -----

  template <typename Lhs, typename Rhs>
  struct ContainsTypes;

  template <typename Tuple, typename T, typename... Ts>
  struct ContainsTypes<Tuple, std::tuple<T, Ts...>>
  {
      static const bool VALUE = ContainsType<Tuple, T>::VALUE && ContainsTypes<Tuple, std::tuple<Ts...>>::VALUE;
  };

  template <typename Tuple>
  struct ContainsTypes<Tuple, std::tuple<>>
  {
      static const bool VALUE = true;
  };

这篇关于检查一组类型是否为另一组的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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