Is there a range class in C++11 for use with range based for loops?

前端 未结 8 1283
失恋的感觉
失恋的感觉 2020-11-27 11:33

I found myself writing this just a bit ago:

template 
class range_class {
 public:
   class iterator {
      friend c         


        
8条回答
  •  粉色の甜心
    2020-11-27 11:53

    Here is a simpler form which is working nicely for me. Are there any risks in my approach?

    r_iterator is a type which behaves, as much as possible, like a long int. Therefore many operators such as == and ++, simply pass through to the long int. I 'expose' the underlying long int via the operator long int and operator long int & conversions.

    #include 
    using namespace std;
    
    struct r_iterator {
            long int value;
            r_iterator(long int _v) : value(_v) {}
            operator long int () const { return value; }
            operator long int& ()      { return value; }
            long int operator* () const { return value; }
    };
    template 
    struct range {
            static r_iterator begin() {return _begin;}
            static r_iterator end  () {return _end;}
    };
    int main() {
            for(auto i: range<0,10>()) { cout << i << endl; }
            return 0;
    }
    

    (Edit: - we can make the methods of range static instead of const.)

提交回复
热议问题