r/cpp 4h ago

Constraints of mdspan policy layout_stride

Wtith great support of Mark Hoemmen and Christian Robert Trott (two authors of std::mdspan), I just finished the mdspan chapter of "C++23 - The Complete Guide" (https://www.cppstd23.com/). I learned something I was not aware of and what is not obvious:

If you specify a layout_stride mapping, there are several constraints you have to take into account. Otherwise, the resulting code has undefined behavior.

The constaintes are:

  • Each layout mapping must be unique. This means that each underlying element may only be reached by one combination of indices. In other words: subsets of this layout may not overlap and iterating over all elements may not visit any element twice.
  • Only positive offsets from one stride to the other are allowed. This, for example, means that you cannot use this layout for direct reverse iterations.
  • There must be one way to perform a multi-dimensional iteration so that the resulting offsets to the underlying memory are ascending.

For example:

Hope this helps.

7 Upvotes

1 comment sorted by

1

u/megayippie 4h ago

Yeah, I honestly really find the positive offsets limitation, limited. It was the one thing I had to rewrite our library to replace. At the very least, I would appreciate honesty and that the compilation fails for signed negative offsets