boost::range::join for multiple ranges

后端 未结 1 975
名媛妹妹
名媛妹妹 2020-12-14 19:40

I want to do the following:

std::vector a = {1,2,3}, b = {4,5,6}, c = {7,8,9};

for(auto&& i : join         


        
相关标签:
1条回答
  • 2020-12-14 20:31

    There are two overloads of boost::join

    template<typename SinglePassRange1, typename SinglePassRange2>
    joined_range<const SinglePassRange1, const SinglePassRange2>
    join(const SinglePassRange1& rng1, const SinglePassRange2& rng2)
    
    template<typename SinglePassRange1, typename SinglePassRange2>
    joined_range<SinglePassRange1, SinglePassRange2>
    join(SinglePassRange1& rng1, SinglePassRange2& rng2);
    

    When you do this

    for(auto&& i : boost::join(boost::join(a,b), c)) {
               //  ^^^^        ^^^^ temporary here
               //   ||
               //  calls the const ref overload
    

    You get a temporary joined_range and as those can only bind to const references, the first overload is selected which returns a range that doesn't allow modifying.

    You can work around this if you avoid temporaries:

    #include <boost/range.hpp>
    #include <boost/range/join.hpp>
    
    int main()
    {
        std::vector<int> a = {1,2,3}, b = {4,5,6}, c = {7,8,9};
        auto range = boost::join(a,b);
    
        for(int& i : boost::join(range,c)) {
            i += 1;
            std::cout << i;
        }
    }
    

    Live demo.

    I haven't looked into your variadic functions, but the problem is likely similar.

    0 讨论(0)
提交回复
热议问题