简体   繁体   中英

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

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 (ie, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM