gpt4 book ai didi

c++ - 基于范围的循环和范围类型

转载 作者:搜寻专家 更新时间:2023-10-30 23:51:14 25 4
gpt4 key购买 nike

引用以下在 Range-based for loop 下提到的文本片段

If range_expression is an expression of a class type C that has both a member named begin and a member named end (regardless of the type or accessibility of such member), then begin_expr is __range.begin() and end_expr is __range.end();

The member interpretation is used if the range type has a member named begin and a member named end. This is done regardless of whether the member is a type, data member, function, or enumerator, and regardless of its accessibility. Thus a class like class meow { enum { begin = 1, end = 2}; /* rest of class */ }; cannot be used with the range-based for loop even if the namespace-scope begin/end functions are present.

begin 和end 应该只是范围类型(​​可能返回迭代器类型)的成员函数名称的理解是否正确?很想了解此约束没有任何解决方法背后的技术原因。

最佳答案

您需要提供非成员beginend 函数(或其他可调用对象),这些函数可以通过argument-dependent lookup 找到。 ,或者具有显式命名为 beginend 的成员函数(或可调用对象),它们不带参数,并且返回类似迭代器的对象(即它们应该支持后缀 ++ 和取消引用 *,当然可以使用 == 进行比较。

至于“技术原因”,这是因为基于范围的 for 循环只是普通迭代器 for 循环的语法糖。并且编译器必须知道为“开始”和“结束”迭代器调用哪些函数。

关于c++ - 基于范围的循环和范围类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com