boost::combine, range-based for and structured bindings(boost::combine,基于范围的和结构化绑定)
问题描述
有没有办法让 boost::combine
与结构化绑定和基于范围的 for 一起工作(这样结构绑定中的标识符实际上指向容器的元素而不是嵌套的任何 boost::combine
在幕后使用)?以下(live example)无法编译:
Is there a way to make boost::combine
work with structured bindings and range-based for (so that identifiers in the structure binding actually point to containers' elements instead of nested tuples of whatever boost::combine
uses under the hood)? The following (live example) fails to compile:
#include <boost/range/combine.hpp>
#include <iostream>
int main()
{
std::vector<int> a{1,2,3};
std::vector<int> b{2,3,4};
for (auto [f, s] : boost::combine(a, b))
{
std::cout << f << ' ' << s << std::endl
}
}
推荐答案
真正的答案是使用 boost::tie
或抓取 range-v3 zip()
这实际上产生了一个 std::tuple
.
The real answer is to use either boost::tie
or grab the range-v3 zip()
which actually yields a std::tuple
.
仅用于教育目的的答案只是调整 boost::tuples::cons
的结构化绑定机制.该类型已经有一个 get()
与 ADL 一起工作并做正确的事情,所以我们需要做的就是提供 tuple_size
和 tuple_element
(这最终真的很容易做到,因为 Boost 中已经存在这些确切的特征):
The for educational purposes only answer is just to adapt the structured bindings machinery for boost::tuples::cons
. That type already has a get()
which works with ADL and does the right thing, so all we need to do is provide tuple_size
and tuple_element
(which ends up being really easy to do since these exact traits already exist in Boost):
namespace std {
template <typename T, typename U>
struct tuple_size<boost::tuples::cons<T, U>>
: boost::tuples::length<boost::tuples::cons<T, U>>
{ };
template <size_t I, typename T, typename U>
struct tuple_element<I, boost::tuples::cons<T, U>>
: boost::tuples::element<I, boost::tuples::cons<T, U>>
{ };
}
但实际上不要在实际代码中这样做,因为实际上只有类型作者应该选择加入这种事情.
But don't actually do that in real code, since really only the type author should opt-in to this kind of thing.
这将使结构化绑定正常工作.
That'll make the structured binding just work.
这篇关于boost::combine,基于范围的和结构化绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:boost::combine,基于范围的和结构化绑定
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01