Edit: this overload has been removed from the standard now, it seems.
From cppreference:
constexpr reference operator[](index_type idx) const; constexpr reference operator()(index_type idx) const;
Returns a reference to the
idx
-th element of the sequence. The behavior is undefined ifidx
is out of range (i.e., if it is less than zero or greater than or equal tosize()
).
It makes sense to overload operator[]
for indexing, as a span represents an object that can refer to a contiguous sequence of objects, but why is operator()
, the function call operator, also overloaded for the same purpose? I don't believe there's anything similar to this in the standard library.
It is there because mdspan
, a not-yet-accepted multi-dimensional span type, uses operator()
for indexing. After all, operator[]
only takes one index, while mdspan
needs multiple indexing.
So for the sake of allowing these two types to have as similar an interface as possible, span
also allows operator()
.
Note that using operator()
is a common convention in C++ for multi-dimensional indexing. Eigen and Boost both use it, as do many others.
From the relevant proposal:
span also overloads operator() for element access, to provide compatibility with code written to operate against view.
The view
has been renamed to mdspan
by now, which is not standardized yet.
As correctly noted in Nicol Bolas' answer, mdspan
will use operator()
to accept multiple indices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With