c++ - boost::combine,基于范围的和结构化绑定(bind)

标签 c++ for-loop boost c++17

有没有办法让 boost::combine 与结构化绑定(bind)和基于范围的 for 一起工作(这样结构绑定(bind)中的标识符实际上指向容器的元素,而不是任何嵌套的元组 boost::combine 在后台使用)?以下 ( live example) 无法编译:

#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.


仅出于教育目的的答案只是为 boost::tuples::cons 调整结构化绑定(bind)机制。该类型已经有一个 get() 可以与 ADL 一起工作并做正确的事情,所以我们需要做的就是提供 tuple_sizetuple_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>>
    { };
}

但实际上不要在实际代码中这样做,因为实际上只有类型作者才应该选择加入这种事情。

这将使结构化绑定(bind)正常工作。

关于c++ - boost::combine,基于范围的和结构化绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55585723/

相关文章:

python-2.7 - 如何解释 Python 2.7 中的花式循环?

c++ - 如何使用boost从文件中读取图形?

c++ - 无法使用 Boost stacktrace + backtrace 获取行号

c++ - WndProc 和 DispatchMessage 的奇怪错误。成员函数不存在?

c++ - 通过基类构造函数从驱动类模板值初始化基类数组成员变量

arrays - 从数组生成网格

python - boost python C++函数调用另一个函数错误

c++ - isdigit() 和 isalnum() 给出错误,因为输入是 const char 并且无法转换。其他可能查看输入是否为数字的方法?

c++ - 使用派生类类型初始化模板类的静态数组

c++ - 仅使用按位运算符复制 for 循环的功能