[英]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 :从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.返回对序列中第idx
个元素的引用。 The behavior is undefined ifidx
is out of range (ie, if it is less than zero or greater than or equal tosize()
).如果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?为索引重载operator[]
是有意义的,因为 span 代表可以引用连续对象序列的对象,但为什么operator()
函数调用 operator也出于相同目的重载? 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.之所以存在,是因为mdspan
是一种尚未被接受的多维跨度类型,它使用operator()
进行索引。 After all, operator[]
only takes one index, while mdspan
needs multiple indexing.毕竟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.请注意,使用operator()
是 C++ 中用于多维索引的常见约定。 Eigen and Boost both use it, as do many others. Eigen 和 Boost 都使用它,许多其他人也是如此。
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.该view
现在已重命名为mdspan
,尚未标准化。
As correctly noted in Nicol Bolas' answer, mdspan
will use operator()
to accept multiple indices.正如 Nicol Bolas 的回答中正确指出的那样, mdspan
将使用operator()
来接受多个索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.