Dev*_*ull 13 c++ boost for-loop c++17
有没有一种方法可以boost::combine使用结构化绑定和基于范围的 for(这样结构绑定中的标识符实际上指向容器的元素,而不是内部使用的嵌套元组boost::combine)?以下(实时示例)无法编译:
#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
}
}
Run Code Online (Sandbox Code Playgroud)
真正的答案是使用boost::tie或获取zip()实际产生std::tuple.
仅出于教育目的的答案只是将结构化绑定机制调整为boost::tuples::cons. 那个类型已经有一个get()可以与 ADL 一起工作并且做正确的事情,所以我们需要做的就是提供tuple_size和tuple_element(这最终很容易做到,因为这些确切的特征已经存在于 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>>
{ };
}
Run Code Online (Sandbox Code Playgroud)
但实际上不要在实际代码中这样做,因为实际上只有类型作者应该选择加入这种事情。
这将使结构化绑定正常工作。