boost zip_iterator ignoring const correctness

115 views Asked by At

In the for loop inside the main() function of the following code, I can change the variables inside the variable ab even when the const auto& is used in the loop. Is there any way to avoid this?

#include <functional>
#include <iostream>
#include <vector>
#include <string>

#include <boost/iterator/zip_iterator.hpp>
#include <boost/tuple/tuple.hpp>

using namespace std;

struct MyClass {
  std::vector<int> a{11, 21, 41};
  std::vector<int> b{1, 2, 4};
  typedef boost::zip_iterator<boost::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator>> const_iterator;
  typedef boost::zip_iterator<boost::tuple<std::vector<int>::iterator, std::vector<int>::iterator>> iterator;

  const_iterator begin() const {
    return const_iterator(boost::make_tuple(a.cbegin(), b.cbegin()));
  }
  const_iterator end() const {
    return const_iterator(boost::make_tuple(a.cend(), b.cend()));
  }
  iterator begin() {
    return iterator(boost::make_tuple(a.begin(), b.begin()));
  }
  iterator end() {
    return iterator(boost::make_tuple(a.end(), b.end()));
  }
};


int main(int argc, char** argv)  
{
  MyClass myc;
  for (const auto &ab: myc)
    ab.get<0>() = 66;
  return 0;
}
2

There are 2 answers

0
Simple On BEST ANSWER

If you iterate over a const MyClass then you will get the compile error you desire:

for (const auto &ab: const_cast<MyClass const&>(myc))
    ab.get<0>() = 66;

You can use std::as_const instead of the const_cast:

for (const auto &ab: std::as_const(myc))
    ab.get<0>() = 66;

This works because the const overloads of begin and end will be called instead, and they return a zip_iterator of const iterators.

0
Martin Bonner supports Monica On

Your problem is that myc is not const, so you are iterating through it with a myc::iterator, not a myc::const_iterator.

You then bind ab to the result of indirecting through that iterator. ab.get<0>() will be a const method (because it doesn't change ab), but it returns a reference to a non-const int.

The solution is to use std::as_const(myc) (where you won't even need the const on the declaration of ab).

for (auto &ab: std::as_const(myc))
    ab.get<0>() = 66;  // Error.  Cannot write to const object.