首页 > 解决方案 > 构造 std::tuple 类型的索引数组

问题描述

给定一个包含不同类型元素的元组(没有两个是相同的):

typedef std::tuple<bool, char, int, float, double, std::string> t1;

以及包含限制为这些类型的元素的元组类型(重复和省略是可能的,但没有其他类型):

typedef std::tuple<char, int, int, double, std::string, int, double> t2;

如何std::array为 in 中的元素构造一个包含匹配元素索引的t1in t2

{1, 2, 2, 4, 5, 2, 4}

标签: c++tuplesc++17template-meta-programmingstdtuple

解决方案


当然,这是可行的。
让我们来锻炼一下和相关的机械std::integer_sequencestd::tuple

首先,编写一种方法来获取类似元组的任意类型的单个唯一匹配的索引:

template <class T, class U, std::size_t... N>
static constexpr auto tuple_index_impl(std::index_sequence<N...>) noexcept {
    static_assert((std::size_t() + ... + std::is_same_v<T, std::tuple_element_t<N, U>>) == 1,
        "There is no single exact match");
    return (0 + ... + (N * std::is_same_v<T, std::tuple_element_t<N, U>>));
}
template <class T, class U>
static constexpr std::size_t
tuple_index_v = tuple_index_impl<T, U>(std::make_index_sequence<std::tuple_size_v<U>>());

遗憾的是,它已经不是标准库的一部分。

接下来,使用它来获取所有索引并将它们放入std::array

template <class T, class U, std::size_t... N>
constexpr auto indices_impl(std::index_sequence<N...>) noexcept {
    return std::array<std::size_t, sizeof...(N)>{tuple_index_v<std::tuple_element_t<N, U>, T>...};
}
template <class T, class U>
constexpr auto indices() noexcept {
    return indices_impl<T, U>(std::make_index_sequence<std::tuple_size_v<U>>());
}

使用示例:

for (auto x : indices<t1, t2>())
    std::cout << x << '\n';

在 coliru 上看到它。


推荐阅读