如何允许范围循环在我的类? [英] How to allow range-for loop on my class?
问题描述
我有这样的类:
class Foo {
private:
int a, b,c,d;
char bar;
double m,n
public:
//这里的构造函数
};
我想在我的类上允许range-for循环,例如
Foo foo {/*...*/};
for(auto& f:foo){
// f将是一个特定的顺序,如c,b,d,(int)m,(int)bar,a, b $ b}
如何实现?我在看迭代器,但不知道什么是一个range-for循环的要求。 (请不要问我使用数组或STL类型)
循环定义等同于: p>
for(auto __begin =< begin-expr>,
__end =< end-expr> ;;
__begin!= __end;
++ __ begin){
auto& f = * __ begin;
//循环体
}
其中 ; begin-expr> 是
foo.begin()
或 begin(foo)
如果没有合适的成员函数,同样对于< end-expr>
。 (这是C ++ 11 6.5.4中对规范的简化,对于范围是类类型的 lvalue 的特殊情况)。
所以你需要定义一个支持预增量的迭代器类型 I have a class like this: I wanna allow range-for loop on my class, e.g. How can I achieve this? I was looking at iterator but don't know what are the requirements for a range-for loop. (Please don't ask me to use array or STL type) The loop is defined to be equivalent to: where So you need to define an iterator type that supports pre-increment 这篇关于如何允许范围循环在我的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ++ it
,dereference * it
和比较 i1!= i2
;和公共成员函数
begin(
)
和 end()
;或
begin(foo)
和 end(foo)
,与 foo
在同一命名空间中,以便可以通过参数相关的查找找到它们。
class Foo {
private:
int a,b,c,d;
char bar;
double m,n
public:
//constructors here
};
Foo foo {/*...*/};
for(auto& f : foo) {
//f will be a specific order such as c,b,d,(int)m,(int)bar,a,(int)n
}
for ( auto __begin = <begin-expr>,
__end = <end-expr>;
__begin != __end;
++__begin ) {
auto& f = *__begin;
// loop body
}
<begin-expr>
is foo.begin()
, or begin(foo)
if there isn't a suitable member function, and likewise for <end-expr>
. (This is a simplification of the specification in C++11 6.5.4, for this particular case where the range is a lvalue of class type).++it
, dereference *it
and comparison i1 != i2
; and either
foo
public member functions begin()
and end()
; orbegin(foo)
and end(foo)
, in the same namespace as foo
so that they can be found by argument-dependent lookup.