简体   繁体   English

为什么 std::span 重载函数调用运算符以进行索引?

[英]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 if idx is out of range (ie, if it is less than zero or greater than or equal to size() ).如果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.

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