Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::combine, range-based for and structured bindings

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   
    }
}
like image 247
Dev Null Avatar asked Apr 09 '19 05:04

Dev Null


2 Answers

You can use boost::tie to accomplish this.

#include <boost/range/combine.hpp>
#include <iostream>

int main()
{
    std::vector<int> a{1,2,3};
    std::vector<int> b{2,3,4};
    int f, s;
    for (auto var : boost::combine(a, b))        
    {
        boost::tie(f, s) = var;
        std::cout << f << ' ' << s << std::endl;   
    }
}

Demo.

like image 33
P.W Avatar answered Oct 22 '22 18:10

P.W


The real answer is to use either boost::tie or grab the range-v3 zip() which actually yields a std::tuple.


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.

like image 102
Barry Avatar answered Oct 22 '22 19:10

Barry