我有两个元组——TypeSets 被建模为元组,因此保证每个类型在它们的参数包中最多包含一次,确切地说——(比如 A = std::tuple<T1, T2>
和 B = std::tuple<T2, T3>
),我希望获得与 A
的交集中的类型元组相对应的 typedef和 B
(在本例中为 tuple_intersect<A,B>::type = std::tuple<T2>
)。我该怎么做?
最佳答案
您可以使用 indices trick连同 has_type
(来自 here ):
#include <tuple>
#include <type_traits>
// ##############################################
// from https://stackoverflow.com/a/25958302/678093
template <typename T, typename Tuple>
struct has_type;
template <typename T>
struct has_type<T, std::tuple<>> : std::false_type {};
template <typename T, typename U, typename... Ts>
struct has_type<T, std::tuple<U, Ts...>> : has_type<T, std::tuple<Ts...>> {};
template <typename T, typename... Ts>
struct has_type<T, std::tuple<T, Ts...>> : std::true_type {};
// ##############################################
template <typename S1, typename S2>
struct intersect
{
template <std::size_t... Indices>
static constexpr auto make_intersection(std::index_sequence<Indices...> ) {
return std::tuple_cat(
std::conditional_t<
has_type<
std::tuple_element_t<Indices, S1>,
S2
>::value,
std::tuple<std::tuple_element_t<Indices, S1>>,
std::tuple<>
>{}...);
}
using type = decltype(make_intersection(std::make_index_sequence<std::tuple_size<S1>::value>{}));
};
struct T1{};
struct T2{};
struct T3{};
using A = std::tuple<T1, T2>;
using B = std::tuple<T2, T3>;
int main()
{
static_assert(std::is_same<std::tuple<T2>, intersect<A, B>::type>::value, "");
}
关于c++ - 两个 TypeSets/Tuples 中的公共(public)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41200299/