我必须检查是否给出了两个元组,一个是另一个元组的子集。我找到了这个优雅的解决方案Check if one set of types is a subset of the other。
但是这个解决方案的问题在于它不考虑子类型,例如
using t1 = std::tuple<int, double>;
using t2 = std::tuple<double, int>;
using t3 = std::tuple<t1, t2>;
这将使子集测试失败。
#include <tuple>
#include <type_traits>
template <typename T, typename... Ts>
constexpr bool contains = (std::is_same<T, Ts>{} || ...);
template <typename Subset, typename Set>
constexpr bool is_subset_of = false;
template <typename... Ts, typename... Us>
constexpr bool is_subset_of<std::tuple<Ts...>, std::tuple<Us...>>
= (contains<Ts, Us...> && ...);
原因是如果我们在t1和t3上做了子集,则contains表达式将int与t1进行比较,后者失败。因此,所需的更改是包含搜索子类型的函数。
P.S此代码仅适用于C ++ 17
答案 0 :(得分:2)
如果您对元组嵌套的结构不感兴趣,可以“展平”嵌套元组。这意味着
int main() {
using t1 = std::tuple<int, double>;
using t2 = std::tuple<double, int>;
using t3 = std::tuple<t1, t2>;
static_assert(
std::is_same<
flatten<t3>,
std::tuple<int, double, double, int>
>{}
);
static_assert(false == is_subset_of<t1, t3>);
static_assert(true == is_subset_of< t1, flatten<t3> >);
return 0;
}
flatten
的快速实施可能如下所示。
namespace detail {
template<class... Ts>
struct flatten {
static_assert(sizeof...(Ts) == 0, "recursion break (see specializations)");
template<class... Result>// flattened types are accumulated in this pack
using type = std::tuple<Result...>;
};
template<template<class...> class Nester, class... Nested, class... Ts>
struct flatten<Nester<Nested...>, Ts...> {// if first arg is nested then unpack
template<class... Result>
using type = typename flatten<Nested..., Ts...>::template type<Result...>;
};
template<class T0, class... Ts>
struct flatten<T0, Ts...> {// if `T0` is flat then just append it to `Result...`
template<class... Result>
using type = typename flatten<Ts...>::template type<Result..., T0>;
};
};// detail
template<class... Ts>
using flatten = typename detail::flatten<Ts...>::template type<>;