Boost logo

Boost Users :

Subject: [Boost-users] [range] const-only UDT works as std algos, but not with boost range.
From: John (john2.718281828459045235360287_at_[hidden])
Date: 2016-09-07 17:18:03


A class that exposes a const_iterator, but does not expose a mutable iterator,
works with std:: algorithms and range-for() loop, but does not work with boost
range.

// This works with std algorithms and range-for, but not with boost range.
class C {
public:
     typedef blah const_iterator;
     const_iterator begin() const;
     const_iterator end() const;
};
const C c;
for (auto x : c) { } // OK
std::for_each(std::begin(c), std::end(c), fn); // OK
boost::for_each (c, fn); // ERROR: fails SinglePassRange concept (GCC-6.2)

The workaround is to add a non-const iterator type that is the same as the const
iterator, and to add two additional non-const begin/end methods.

class D {
public:
     typedef blah const_iterator;
     const_iterator begin() const;
     const_iterator end() const;

     // kludge to make it work with boost.
     typedef const_iterator iterator;
     iterator begin();
     iterator end();
};

const D d;
boost::for_each (d, fn); // OK

Is there a simpler solution?


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net