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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With