#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 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()
| ^~~~~
为什么必须有一个 std::ranges::filter_view
对象对于查询其元素来说是非常量吗?
为了提供所需的摊余常量时间复杂度range
, filter_view::begin
将结果缓存在*this
。这会修改内部状态*this
因此不能在const
成员函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)