#include <ranges>
#include <iostream>
#include <string_view>
using namespace std::literals;
int main()
{
auto fn_is_l = [](auto const c) { return c == 'l'; };
{
auto v = "hello"sv | std::views::filter(fn_is_l);
std::cout << *v.begin() << std::endl; // ok
}
{
auto const v = "hello"sv | std::views::filter(fn_is_l);
std::cout << *v.begin() << std::endl; // error
}
}
See: https://godbolt.org/z/vovvT19a5
<source>:18:30: error: passing 'const std::ranges::filter_view<
std::basic_string_view<char>, main()::
<lambda(auto:15)> >' as 'this' argument discards
qualifiers [-fpermissive]
18 | std::cout << *v.begin() << std::endl; // error
| ~~~~~~~^~
In file included from <source>:1:/include/c++/11.1.0/ranges:1307:7:
note: in call to 'constexpr std::ranges::filter_view<_Vp,
_Pred>::_Iterator std::ranges::filter_view<_Vp, Pred>
::begin() [with _Vp = std::basic_string_view<char>; _Pred =
main()::<lambda(auto:15)>]'
1307 | begin()
| ^~~~~
Why must a std::ranges::filter_view
object be non-const for querying its elements?
In order to provide the amortized constant time complexity required by range
, filter_view::begin
caches the result in *this
. This modifies the internal state of *this
and thus cannot be done in a const
member function.