How to make my custom type to work with “range-based for loops”?

后端 未结 9 2265
长情又很酷
长情又很酷 2020-11-22 08:06

Like many people these days I have been trying the different features that C++11 brings. One of my favorites is the \"range-based for loops\".

I understand that:

9条回答
  •  滥情空心
    2020-11-22 08:21

    Should I just specialize begin() and end() ?

    As far as I know, that is enough. You also have to make sure that incrementing the pointer would get from the begin to the end.

    Next example (it is missing const version of begin and end) compiles and works fine.

    #include 
    #include 
    
    int i=0;
    
    struct A
    {
        A()
        {
            std::generate(&v[0], &v[10], [&i](){  return ++i;} );
        }
        int * begin()
        {
            return &v[0];
        }
        int * end()
        {
            return &v[10];
        }
    
        int v[10];
    };
    
    int main()
    {
        A a;
        for( auto it : a )
        {
            std::cout << it << std::endl;
        }
    }
    

    Here is another example with begin/end as functions. They have to be in the same namespace as the class, because of ADL :

    #include 
    #include 
    
    
    namespace foo{
    int i=0;
    
    struct A
    {
        A()
        {
            std::generate(&v[0], &v[10], [&i](){  return ++i;} );
        }
    
        int v[10];
    };
    
    int *begin( A &v )
    {
        return &v.v[0];
    }
    int *end( A &v )
    {
        return &v.v[10];
    }
    } // namespace foo
    
    int main()
    {
        foo::A a;
        for( auto it : a )
        {
            std::cout << it << std::endl;
        }
    }
    

提交回复
热议问题