c++ - 两个 TypeSets/Tuples 中的公共(public)类型

标签 c++ tuples c++14 metaprogramming

我有两个元组——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, "");
}

live example

关于c++ - 两个 TypeSets/Tuples 中的公共(public)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41200299/

相关文章:

c++ - 如何测量C math.h库函数的执行时间?

android - cv::cvtColor 没有分配内存问题

python - 解压元组内的元组

python - 将元组扩展为参数

C++14:具有通用 std::function 作为类成员的通用 lambda

c++ - 有没有办法在 C++ 中反转数组的顺序?

python - 在保持标签的同时将大范围压缩为 python 中的较短范围

c++ - C++17 中的歧义错误(模板模板参数和默认参数问题)

c++ - SFINAE 与特征检测部门有关的问题

c++ - 在 C++ 中填充动态分配的数组