18

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.

4

2 回答 2

23

它在那里是因为mdspan一种尚未被接受的多维跨度类型operator()用于索引。毕竟operator[]只需要一个索引,而mdspan需要多个索引。

所以为了让这两种类型有尽可能相似的接口,span也允许operator().

请注意, usingoperator()是 C++ 中用于多维索引的常见约定。Eigen 和 Boost 都使用它,许多其他人也使用它。

于 2018-04-29T16:53:57.857 回答
10

来自相关提案

span 还为元素访问重载了 operator(),以提供与针对视图操作而编写的代码的兼容性。

到现在view已经改名了mdspan,还没有标准化。

正如 Nicol Bolas 的回答中正确指出的那样,mdspan将用于operator()接受多个索引。

于 2018-04-29T16:57:15.823 回答