【问题标题】:Check if tuple types are subsets of each other检查元组类型是否是彼此的子集
【发布时间】:2016-04-11 16:24:37
【问题描述】:

假设我有 2 个未实例化的元组。有没有一种惯用的方法来检查一个集合是否是另一个集合的子集?

如果这需要其他类型而不是hana::tuple_c,这也可以。实际上,我当前的输入由std::tuple 组成,但我无法让它工作。

工作的代码(但我觉得应该有类似的可能):

#include <boost/hana.hpp>
using namespace boost;

using SetA = hana::tuple_c<int, char, float>;
using SetB = hana::tuple_c<int, float>;

static_assert(
    hana::is_subset( SetB, SetA ),
    ""
);

我当前的解决方法是使用boost::mpl 进行交集,然后比较结果。这可行,但我对纯 boost::hana 解决方案感兴趣:

#include <boost/mpl.hpp>
using namespace boost;

using SetA = mpl::set<int, char, float>;
using SetB = mpl::set<int, float>;

using Intersection = typename mpl::copy_if<
    SetA,
    mpl::has_key< SetB, mpl::_1 >,
    mpl::back_inserter< mpl::vector<> >
>::type;

// since Intersection is a vector, subset also needs vector type
using Subset = typename mpl::copy<
    SetB,
    mpl::back_inserter< mpl::vector<> >
>::type;

static_assert(std::is_same<Intersection, Subset>::value, "");

【问题讨论】:

    标签: c++ boost-mpl boost-hana


    【解决方案1】:

    您没有正确使用boost::hana。这将起作用:

    #include <boost/hana.hpp>
    using namespace boost;
    
    constexpr auto setA = hana::tuple_t<int, char, float>;
    constexpr auto setB = hana::tuple_t<int, float>;
    
    // Is `setB` a subset of `setA`? (Yes.)
    static_assert(hana::is_subset(setB, setA), "");
    
    // Is `setA` a subset of `setB`? (No.)
    static_assert(!hana::is_subset(setA, setB), "");
    

    解释:

    hana::tuple_t&lt;xs...&gt;hana::type_c 对象元组的简写符号。

    • auto x = hana::tuple_t<int, char>;
      // ...is equivalent to...
      auto x = hana::make_tuple(hana::type_c<int>, hana::type_c<char>);
      

    hana::type_c 对象将类型包装成值。

    hana::is_subset(a, b) 检查 a 是否是 b 的子集,而不是反之亦然 (您在问题中检查 b 是否是 a 的子集).

    【讨论】:

      猜你喜欢
      • 2017-07-23
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 2019-04-05
      • 2023-03-18
      • 2015-06-08
      • 1970-01-01
      相关资源
      最近更新 更多