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;
}
If you iterate over a
const MyClass
then you will get the compile error you desire:You can use
std::as_const
instead of theconst_cast
:This works because the
const
overloads ofbegin
andend
will be called instead, and they return azip_iterator
of const iterators.