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.

7
  • 3
    Do yourself a favor and use std::array instead. Commented Apr 6, 2017 at 13:06
  • The size is unkown at compile-time, I used n as example. Commented Apr 6, 2017 at 13:08
  • 2
    Use an std::vector then. Commented Apr 6, 2017 at 13:08
  • @user2370139 C++ does not allow you to cast a raw pointer to an array type . So no. You need to implement this solution: stackoverflow.com/a/12444983/126769 Commented Apr 6, 2017 at 13:10
  • 2
    You could use a gsl::span Commented Apr 6, 2017 at 13:13

1 Answer 1

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.

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

7 Comments

Isn't it UB to add these overloads into the std namespace?
Not, I think, for template specialisations; even partial ones. Cf std::hash. Perhaps an expert can confirm.
I think that who worked on standard should think about using result of std::equal_range in for range loop.
@NathanOliver: [C++14: 17.6.4.2.1/1] looks ok iff T is user-defined.
@BoundaryImposition: But we cannot add this restriction on T (via std::enable_iffor 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.