1

I have a pointer "a", it is of type A*. I now that there is n objects of type A at that address and I want to iterate over them.

I would like to cast it to A[n], so that I can use the c++11 range-for and write for (auto temp : a){...}. Of course, I can use a classic for(int i=0; i<n; i++) {temp=a[i]; ...} but the range-for is cleaner.

user2370139
  • 1,297
  • 1
  • 11
  • 13

1 Answers1

1

In reasonable code, I'd shy away from it. But C++ allows you to commit acts of sheer devilry. In that vein, I offer a solution:

At the expense of some considerable obfuscation, you can write some preparatory templates:

namespace std
{
    template <typename T> T* begin(std::pair<T*, T*> const& a)
    {
        return a.first;
    }

    template <typename T> T* end(std::pair<T*, T*> const& a)
    {
        return a.second;
    }
}

Then you can write something like

for (auto&& i : std::make_pair(a, a + n)){

}

The template stuff brings in suitable definitions of begin and end which is required by the range for loop.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483