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()
).返回对序列的第idx个元素的引用。如果idx超出范围(即,如果它小于零或大于或等于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.
重载operator []进行索引是有意义的,因为span表示可以引用连续对象序列的对象,但为什么operator()(函数调用运算符)也为了相同的目的而重载?我不相信标准库中有类似的东西。
2 个解决方案
#1
21
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.
它就在那里,因为mdspan是一种尚未被接受的多维跨度类型,它使用operator()进行索引。毕竟,operator []只接受一个索引,而mdspan需要多个索引。
So for the sake of allowing these two types to have as similar an interface as possible, span
also allows operator()
.
因此,为了允许这两种类型具有尽可能相似的接口,span还允许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.
请注意,使用operator()是C ++中用于多维索引的常见约定。与许多其他人一样,Eigen和Boost都使用它。
#2
8
From the relevant proposal:
从相关提案:
span also overloads operator() for element access, to provide compatibility with code written to operate against view.
span还重载operator()以进行元素访问,以提供与为视图操作而编写的代码的兼容性。
The view
has been renamed to mdspan
by now, which is not standardized yet.
到目前为止,视图已重命名为mdspan,尚未标准化。
As correctly noted in Nicol Bolas' answer, mdspan
will use operator()
to accept multiple indices.
正如Nicol Bolas的回答中正确指出的那样,mdspan将使用operator()接受多个索引。
#1
21
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.
它就在那里,因为mdspan是一种尚未被接受的多维跨度类型,它使用operator()进行索引。毕竟,operator []只接受一个索引,而mdspan需要多个索引。
So for the sake of allowing these two types to have as similar an interface as possible, span
also allows operator()
.
因此,为了允许这两种类型具有尽可能相似的接口,span还允许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.
请注意,使用operator()是C ++中用于多维索引的常见约定。与许多其他人一样,Eigen和Boost都使用它。
#2
8
From the relevant proposal:
从相关提案:
span also overloads operator() for element access, to provide compatibility with code written to operate against view.
span还重载operator()以进行元素访问,以提供与为视图操作而编写的代码的兼容性。
The view
has been renamed to mdspan
by now, which is not standardized yet.
到目前为止,视图已重命名为mdspan,尚未标准化。
As correctly noted in Nicol Bolas' answer, mdspan
will use operator()
to accept multiple indices.
正如Nicol Bolas的回答中正确指出的那样,mdspan将使用operator()接受多个索引。