c++ - 构造 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 中的元素构造一个包含匹配元素索引的t1
in t2
?
{1, 2, 2, 4, 5, 2, 4}
解决方案
当然,这是可行的。
让我们来锻炼一下和相关的机械std::integer_sequence
。std::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 上看到它。
推荐阅读
- java - 无法删除父行:外键约束失败
- laravel - Composer 更新或安装问题
- java - 执行表单验证android的最佳方法
- java - 我正在使用 java 16.1,但我遇到了这个问题,运行代码时出现 Spring boot 错误
- javascript - 是他们减少 TBT 总阻塞时间和主线程工作的任何方法吗?到目前为止,我已经完成了以下优化更改
- regex - 解析日志文件以获取一行中的一些值
- css - 我一直在为与创建 4 层导航栏相关的 CSS 样式而苦苦挣扎。请帮我解释
- amazon-web-services - Aws ALB 运行状况检查
- python - 如何在 django 模型中获取图像文件大小?
- ios - 多个 RCTRootView 共享一个 RTCbridge