c++ - 多次使用 [x, y, z, ...]-clause 语法,不应该允许 operator[] 接受多个参数吗?

标签 c++ operator-overloading c++17 square-bracket

从 C++11 开始,我们可以编写 lambda,例如:

auto foo = [a, b]() { return a+b; };

带有方括号的捕获子句,其中的项目由逗号分隔。在 C++17 中,我们将能够使用结构化绑定(bind):

for (const auto& [name, description] : planet_descriptions) {
    std::cout << "Planet " << name << ":\n" << description << "\n\n";
}

这是逗号分隔的方括号子句的另一个示例。

但是,我们不能覆盖类' operator[]采取几个参数,例如这个:

template<typename V, typename I, typename J>
const V& operator[](I i, J j) const {
    return data_[width() * i + j];
}

not compile .

我知道有变通办法——这里提到了很多:

C++ [] array operator with multiple arguments?

但是——为什么前者是语言的一部分,而后者是不可能的,即使是程序员自行决定的重载?仅仅是因为没有人提出其他建议,还是有一些特定的原因?

注意事项:

  • 是的,当然这会产生歧义/与在调用一元 operator[] 时使用逗号运算符不兼容。 : x[a, b]要么是 operator[](operator,(a,b))operator[](a,b) .然而,我们对圆括号有同样的歧义:foo(a,b)可能是对二进制 foo() 的调用与 ab ,或者它可能是 foo(operator,(a,b) .语言标准只是规定它是前者而不是后者(或者前者应该是首选);可以对方括号给予同样的优先权。事实上,如果我没记错的话,那实际上不会破坏任何现有代码——因为现有代码不会有二进制 operator[]。更喜欢。
  • 示例二进制文件 operator[]只是一个例子,不是我想要实现的。

最佳答案

这当然是一个选择,尽管对许多人来说令人惊讶,因为一般倾向于坚持 C 程序员熟悉的运算符的 C 语法。

这也不是一个新想法,Gabriel Dos Reis 在 2014 年提出。该想法的最后记录状态来自 Uniform handling of operator[] and operator()如下:

In c++std-core-14770, Dos Reis suggests that operator[] and operator() should both be allowed to be static. In addition to that, he suggests that both should allow multiple parameters. It's well known that there's a possibility that this breaks existing code (foo[1,2] is valid, the thing in brackets is a comma-expression) but there are possibilities to fix such cases (by requiring parens if a comma-expression is desired). EWG should discuss whether such unification is to be strived for.

Discussed in Rapperswil 2014. EWG points out that there are more issues to consider here, in terms of other operators, motivations, connections with captureless lambdas, who knows what else, so an analysis paper is requested.

所以用这位著名的 C++ 语言理论家的话来说:如果你喜欢它,那就写一篇关于它的论文。

关于c++ - 多次使用 [x, y, z, ...]-clause 语法,不应该允许 operator[] 接受多个参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43824941/

相关文章:

c++ - OpenCV 3.0 中缺少 cv::Mat.refcount

c++ - inotify 和 epoll 的区别

c++ - libvncserver/libvncclient websocket支持(至vSphere)?

c++ - 我应该从以下功能中选择什么

c++ - 实验性 make_array,我可以使用 brace-init 列表作为参数吗?

c++ - 如何使用性能计数器控制从文件中读取?

c++ - 如何在 C++ 中将远程设备映射为数组?

c++ - 创建具有多态性和 op 的模板。 C++中的重载

c++ - 使用 boost::hana 创建一个大的编译时间映射

c++ - 有没有办法禁用非动态类构造函数?