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

后端 未结 9 2189
长情又很酷
长情又很酷 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:40

    Inspired by BitTickler's comment about how to make it work for non-"container" types, here's a minimal example of something that works for doubles:

    class dranged {
        double start, stop, step, cur;
        int index;
    
    public:
        dranged(double start, double stop, double step) :
            start(start), stop(stop), step(step),
            cur(start), index(0) {}
    
        auto begin() { return *this; }
        auto end() { return *this; }
    
        double operator*() const { return cur; }
    
        auto& operator++() {
            index += 1;
            cur = start + step * index;
            return *this;
        }
    
        bool operator!=(const dranged &rhs) const {
            return cur < rhs.stop;
        }
    };
    

    Note that the use of < in the != operator maintains the correct invariant, but obviously assumes step is positive and wouldn't be appropriate everywhere a more general range would be. I've used an integer index to prevent propagation of floating point error, but have aimed for simplicity otherwise.

    This can be used as:

    double sum() {
        double accum = 0;
        for (auto val : dranged(0, 6.28, 0.1)) {
            accum += val;
        }
        return accum;
    }
    

    GCC and Clang both produce very reasonable code when compiled with optimisations (i.e. either -Os or above -O1 for GCC or -O2 for Clang).

提交回复
热议问题