gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:09:37 26 4
gpt4 key购买 nike

编辑:现在看来,这个重载已经从标准中删除了。

来自 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()).

重载 operator[] 用于索引是有意义的,因为 span 表示可以引用连续对象序列的对象,但为什么是 operator() , function call operator ,也出于同样的目的而重载?我不相信标准库中有类似的东西。

最佳答案

它在那里是因为 mdspan, a not-yet-accepted multi-dimensional span type , 使用 operator() 进行索引。毕竟 operator[] 只需要一个索引,而 mdspan 需要多个索引。

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

请注意,使用 operator() 是 C++ 中用于多维索引的常见约定。 Eigen 和 Boost 都使用它,还有很多其他的。

关于c++ - 为什么 std::span 会重载函数调用运算符以进行索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50089054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com