Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force foreach to use const iterators

I have a custom container class which implements cbegin() and cend() functions. Then I use it in a foreach loop, but it seems to require begin() and end() member functions, even though I tried using const modifier:

for (const auto val: container)

and like this:

for (auto const val: container)

and like this:

for (const auto const val: container)

Is it possible to force foreach to use constant c-functions?

like image 683
Max Avatar asked Nov 12 '13 21:11

Max


1 Answers

Sure: make the range appear as if it is a const range:

template <typename T>
T const& make_const(T const& argument) {
    return argument;
}

// ...
for (auto&& value: make_const(argument)) {
    ...
}

In all cases the range-based for will, however, use begin() and end() and never cbegin() or cend(). You might want to provide these instead:

template <typename T>
auto begin(my_container<T> const& t) -> decltype(t.cbegin()) {
    return t.cbegin();
}
template <typename T>
auto end(my_container<T> const& t) -> decltype(t.cend()) {
    return t.cend();
}

Obviously, you want to replace my_container by a suitable container type. Personally, I would probably just provide suitable begin() and end() members.

like image 78
Dietmar Kühl Avatar answered Oct 13 '22 10:10

Dietmar Kühl