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

  • A+
Category:Languages

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.


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: