如何在我的课堂上允许 range-for 循环?

2022-01-10 00:00:00 iterator c++ c++11

我有这样的课:

class Foo {
private:
    int a,b,c,d;
    char bar;
    double m,n
public:
    //constructors here
};

我想在我的课堂上允许 range-for 循环,例如

I wanna allow range-for loop on my class, e.g.

Foo foo {/*...*/};
for(auto& f : foo) {
  //f will be a specific order such as c,b,d,(int)m,(int)bar,a,(int)n
}

我怎样才能做到这一点?我正在查看迭代器,但不知道 range-for 循环的要求是什么.(请不要让我使用数组或STL类型)

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)

推荐答案

循环定义为等价于:

for ( auto __begin = <begin-expr>,
           __end = <end-expr>;
      __begin != __end;
      ++__begin ) {
    auto& f = *__begin;
    // loop body
}

其中 <begin-expr>foo.begin(),如果没有合适的,则为 begin(foo)成员函数,对于 <end-expr> 也是如此.(这是对 C++11 6.5.4 中规范的简化,适用于范围是类类型的 lvalue 的这种特殊情况.

where <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、解引用*it和比较i1 != i2;或者

So you need to define an iterator type that supports pre-increment ++it, dereference *it and comparison i1 != i2; and either

  • foo 公共成员函数 begin()end();或
  • 定义非成员函数begin(foo)end(foo),和foo在同一个命名空间,这样它们就可以通过依赖于参数的查找找到.
  • give foo public member functions begin() and end(); or
  • define non-member functions begin(foo) and end(foo), in the same namespace as foo so that they can be found by argument-dependent lookup.

相关文章