Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::span overload the function call operator for indexing?

Tags:

c++

c++20

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 if idx is out of range (i.e., if it is less than zero or greater than or equal to size()).

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.

like image 915
Mário Feroldi Avatar asked Apr 29 '18 16:04

Mário Feroldi


2 Answers

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.

like image 182
Nicol Bolas Avatar answered Nov 10 '22 21:11

Nicol Bolas


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.

like image 10
Baum mit Augen Avatar answered Nov 10 '22 23:11

Baum mit Augen