检查元组类型是否是彼此的子集

Check if tuple types are subsets of each other

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

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

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

#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, "");

您没有正确使用 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<xs...> 是 shorthand 表示 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) 检查 如果 ab 的子集,反之亦然 (您正在检查是否b 是您问题中 a 的子集).