如何允许范围循环在我的类? [英] How to allow range-for loop on my class?

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

问题描述

我有这样的类:

  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 的特殊情况)。



所以你需要定义一个支持预增量的迭代器类型 ++ it ,dereference * it 和比较 i1!= i2 ;和公共成员函数 begin( end();或

  • 定义非成员函数 begin(foo) end(foo),与 foo 在同一命名空间中,以便可以通过参数相关的查找找到它们。


  • I have a class like this:

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

    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
    }
    

    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:

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

    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).

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

    • 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.

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

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