c++ - 为什么 std::ranges::filter_view 对象必须是非常量才能查询其元素?

标签 c++ constants standards c++20 std-ranges

#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
    }
}
见: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 中完成成员函数。

关于c++ - 为什么 std::ranges::filter_view 对象必须是非常量才能查询其元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67667318/

相关文章:

mysql - 这是 MySQL 的良好做法吗

c++ - 在 C++ 中编写一个检查内存泄漏的测试用例

c++ - 有没有办法使类递归?

angular - 使用可注入(inject) token 处理全局常量 Angular 4

c - 错误 : expression must have a constant value

Java final 与 C++ const

c++ - 使用单参数模板化构造函数从引用元组构造值元组

c++ - 完整的 C++ i18n gettext() "hello world"示例

c++ - 下溢或上溢的指针会发生什么情况?

c++ - 所有模板参数包的默认值都是 "empty"吗?