c++ - Range-v3: Use view_facade to provide both const and non-const iterators -


i having trouble using view_facade (from range-v3) create view provides both const , non-const access. example, tried modifying view_facade test (in test/view_facade.cpp) allow non-const access (by default allows const access):

struct myrange   : ranges::range_facade<myrange> { private:     friend struct ranges::range_access;     std::vector<int> ints_;      template <bool isconst>     struct cursor     {     private:         using = typename std::conditional<isconst, std::vector<int>::const_iterator, std::vector<int>::iterator>::type;         using reftype = typename std::conditional<isconst, int const&, int&>::type;         iter;     public:         cursor() = default;         cursor(it it)           : iter(it)         {}         reftype current() const         {             return *iter;         }     //...     }; /*    // uncommenting these overloads cause error, below.     cursor<true> begin_cursor() const     {         return {ints_.begin()};     }     cursor<true> end_cursor() const     {         return {ints_.end()};     } */     cursor<false> begin_cursor()     {         return {ints_.begin()};     }     cursor<false> end_cursor()     {         return {ints_.end()};     } public:     myrange()       : ints_{1, 2, 3, 4, 5, 6, 7}     {} };  int main() {     myrange nc;     int& nci = *nc.begin();  // error here when const overloads present. } 

full code here.

this works fine const overloads of begin_cursor , end_cursor commented out. however, if add overloads in, following error generated on indicated line (gcc 5.1):

error: binding 'const int' reference of type 'int&' discards qualifiers 

it seems selecting const version, giving me const iterator. want is: const iterators const objects, , non-const iterators non-const objects. how can achieve that?

view_facade building views. views refer data don't own. pointers in logically indirections. , pointers, top-level const should have no effect on const-ness of data referenced. whether dereference int* or int*const, result same: int&.

your view not view. owns data. (see vector<int> ints_ data member.) trying use view_facade turn data structure view bound lead frustration. design. views distinct containers. range-v3 library doesn't come container facade, sorry.

(what's going on: since views represent indirection, view_facade tries hard make const , non-const begin() , end() return same types. if cursor_begin() const present, 1 always chosen. always. when breaks code, it's because code confusing containers views.)


Comments