如何在我的课堂上允许 range-for 循环? [英] How to allow range-for loop on my class?

查看:16
本文介绍了如何在我的课堂上允许 range-for 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的课:

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.

这篇关于如何在我的课堂上允许 range-for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆