c++boostiteratorboost-iterators

boost zip_iterator ignoring const correctness


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;
}

Solution

  • 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.