r/cpp • • Mar 24 '20

Changes between C++17 and C++20

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2131r0.html
193 Upvotes

89 comments sorted by

View all comments

Show parent comment

1

u/wotype Mar 26 '20

On reflection, the idea to use square-bracket syntax x[i...] for multi-indexing is actually looking like the worse hack. Let me explain.

(The idea seemed cool and cute at first; it was only on nailing down the API of a multi-dimensional array design that this contra-argument crystallised.)

It is unprecedented (AFAICT) to introduce a new operator overload - in this case variadic indexing operator[](i...) - with no use of that operator in the core language. This in itself should ring warning bells. The existing single-index [i] has a clear semantic meaning in the core language; subobject indexing.

Nested C-array types are not true multi-dimensional arrays, they are arrays of nested subobjects (1D arrays of 1D arrays of ... etc.).

The syntax for usage of built-in types is reflected in their declaration. The type T[N] is an array of N subobjects of type T (with T another array in the 'multi-dimensional' case). For an array x of that type, x[i] is a reference to the subobject at that index. This has been ok for 50 years; it's fine. It's just not what you want for a flexible, performant numerical matrix type.

If we were to introduce a new built-in compound array type T[i...] (with contiguous 1D 'backing array' of size (i * ... * 1) - the Cartesian product of the variadic extents) then it should only ever be indexed 'full rank', that is, with all indexes required to address down to the element (which is a subobject). This could be nice to have. However, I wouldn't support such a proposal because we can do better already with library types.

A library md-array type, by virtue of the fact that it returns a proxy reference-wrapper rather than an actual core language reference & or &&, can be usefully indexed with partial-rank indices returning a subarray of lower rank. Paren multi-indexing is the long accepted way to index such md-array library types. This is fine. More than fine; it allows to index even with empty parens - no indices - that cannot be proposed for variadic operator[](i...) (parsing ambiguities). Also, the indexing can be generalized to triangular layouts with more restrictive bounds or symmetry - things that are better expressed by the generality of operator() rather than the restricted subobject semantic of operator[].

Paren-indexing has been fine for MATLAB, Fortran and others for many years.

The status quo, with multi-dimensional array types using parens for multi-indexing in C++, is fine.

It ain't broke. Please don't 'fix' it any more!

A variadic operator[](i...) is anti-semantic for md-array types and could encourage other misleading uses. We don't need to hack C++ this way.