如何在std::apply中获取当前tuple元素索引用于std::array的std::get<>()
解决std::apply中关联tuple元素索引与std::array的问题
要实现tuple元素与std::array对应位置对象的绑定调用,核心是在std::apply展开参数包时获取每个元素的索引。这里提供两种简洁的实现方式:
方法一:通过std::tuple_cat绑定索引序列与原tuple
直接将原tuple和生成的索引序列打包成新tuple,让std::apply同时展开元素和索引:
std::apply( [this](auto&&... tuple_item, auto... indices) { // 折叠表达式遍历每个索引与tuple元素,调用对应array对象的func ((std::get<indices>(this->my_std_array_member).func(tuple_item.name)), ...); }, // 将原tuple与索引序列合并为新tuple std::tuple_cat(my_std_tuple, std::make_index_sequence<std::tuple_size_v<decltype(my_std_tuple)>>{}) );
说明
std::make_index_sequence<N>会生成0,1,...,N-1的编译期索引序列,N由原tuple的大小推导std::tuple_cat把原tuple的元素和索引序列打包,std::apply展开时就能同时拿到每个tuple元素和它对应的索引- 折叠表达式确保每个array对象都能以对应tuple元素的
name为参数调用func
方法二:单独编写模板函数利用索引序列
如果觉得tuple_cat的方式不够直观,可以单独写一个模板函数,直接通过索引访问tuple和array的对应位置:
// 模板函数:通过索引序列同步访问tuple和array template<typename Tuple, std::size_t... Is> void process_members(const Tuple& tuple, std::index_sequence<Is...>) { ((std::get<Is>(this->my_std_array_member).func(std::get<Is>(tuple).name)), ...); } // 调用处 process_members(my_std_tuple, std::make_index_sequence<std::tuple_size_v<decltype(my_std_tuple)>>{});
说明
- 模板参数
Is...接收编译期索引序列,通过std::get<Is>分别访问tuple和array的对应元素 - 这种方式逻辑更直接,适合需要复用该逻辑的场景
注意事项
- 必须保证tuple和std::array的大小完全一致,否则编译时会触发
std::get的越界错误 - 如果tuple元素是可移动类型,可将参数改为
auto&& tuple并使用std::forward转发,避免不必要的拷贝
内容的提问来源于stack exchange,提问作者amigo421
相关产品推荐
相关产品推荐

