Vin*_*ent 3 c++ standards multidimensional-array subscript c++11
目前,我们只能operator[]用一个参数重载.
我想知道是否有一个根本原因,为什么标准不允许operator[]多个参数重载?
对于C++ 17,是否有这样的propoposals?
我想知道是否有一个根本原因,为什么标准不允许
operator[]多个参数重载?
没有根本原因; 只是重载运算符与它们重载的内置运算符具有相同语法的一般原则.
对于C++ 17,是否有这样的propoposals?
不是.一种常见的替代方案是超载operator(); 你可以根据自己的喜好选择多少参数.
这可能是可以添加的,但不应该添加,因为它会破坏现有代码.
基本上,多个参数operator[]意味着以下将编译:
struct Foo
{
int operator[](int a, int b, int c)
{
return 0;
}
}
int main()
{
Foo foo;
auto n = foo[1, 2, 3]; // list of parameters
}
Run Code Online (Sandbox Code Playgroud)
但考虑一下:
int main()
{
Foo foo;
std::vector<int> bar(4, 0);
auto n = foo[1, 2, 3]; // list of parameters
auto x = bar[1, 2, 3]; // comma operator! returning the 3rd element of bar. valid syntax
}
Run Code Online (Sandbox Code Playgroud)
这意味着,在方括号内使用逗号的表达式可以是参数列表或使用逗号运算符.因此,operator []的参数只能有一个有效数字,这意味着无法解决:
struct Foo
{
int operator[](int a, int b, int c)
{
return 0;
}
int operator[](int a)
{
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
没有办法消除1, 2, 3这里的含糊之处.这意味着:如果标准将更改为允许此项,则在调用中使用逗号运算符的任何代码operator[]都将成为编译错误.标准委员会努力不破坏现有代码(这是一件好事!)随着新功能的引入.在我看来,这将是一个彻底的改变,因此不太可能完成.
如果你想要多个参数,要么使用不同的运算符(如Mike建议的operator()那样),要么传递一个std::tuple或等价的.
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |