boost :: combine,基于范围的for和结构化绑定 [英] boost::combine, range-based for and structured bindings

查看:64
本文介绍了boost :: combine,基于范围的for和结构化绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使boost::combine与结构化绑定和基于范围的for一起使用(以便结构绑定中的标识符实际上指向容器的元素,而不是boost::combine在幕后使用的嵌套元组)?以下内容(实时示例)无法编译:

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_sizetuple_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,基于范围的for和结构化绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆