3

I have a dynamic array wrapper template like this:

class Wrapper {
  public:
    T* const start;
    T* const end;
    T* begin() const { return start; }
    T* end() const { return end; }
    /*
       more code
    */
};

which gives value and reference access via the loops:

Wrapper<T> wrapper;
for(auto val : wrapper) {
  //do smth to value
}
for(auto& ref : wrapper) {
  //do smth to reference
}

. I now want to create a range based for loop which is equivalent to this:

for(auto ptr = wrapper.start; ptr != wrapper.end; ptr++) {
  //do smth to pointer
}

, i.e. I want a range based loop over wrapper to give access to a pointer. Is there a way to do this without creating an array of pointers to pointers inside my wrapper?

Edit:

Dani's solution in the comment works as has already been pointed out here. I was actually wondering if there was a way to make the following syntax:

for(auto ptr : wrapper) {
  //do smth
}

work as the C-style for loop above.

2
  • You can take a pointer from the reference Commented Oct 13, 2016 at 19:33
  • You mean something like: for(auto& ref : wrapper) { auto ptr = &ref; } ? Can I somehow alter the begin() and end() methods to get this working implicitly insite this: for(auto ptr : wrapper) { /* do smth */ } ? Commented Oct 13, 2016 at 19:48

1 Answer 1

1

You could write your own custom iterator that returns a T* when dereferenced

class iterator {
    T* ptr;
public:
    explicit iterator(T* ptr) : ptr(ptr) {}
    iterator& operator++() {ptr++; return *this;}
    bool operator!=(iterator other) const {return ptr != other.ptr;}
    T* operator*() const {return ptr;}
};

And then return this iterator from your begin and end functions.

I think it is slightly surprising behavior for an array wrapper to have though.

Live demo.

Sign up to request clarification or add additional context in comments.

1 Comment

That looks great. Thanks. The array wrapper is just a minimal example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.