gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:01 25 4
gpt4 key购买 nike

假设我有 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...> 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 的子集)

关于c++ - 检查元组类型是否是彼此的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34652445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com