为什么c++设计者选择不允许非成员operator()()

Why did the C++ designers choose not to allow non-member operator()()?

本文关键字:成员 operator 不允许 c++ 设计者 选择 为什么      更新时间:2023-10-16

我只是在玩std::function<>operator s,使c++语句看起来像函数式语言(F#),并发现operator()operator<<之间存在差异。我的代码:

函数1(操作符重载):

function<int(int)> operator>>(function<int(int)> f1, function<int(int)> f2)
{
  function<int(int)> f3 = [=](int x){return f1(f2(x));};
  return f3;
}

函数2(操作符重载):

function<int(int, int)> operator>>(function<int(int, int)> f1, function<int(int)> f2)
{
  function<int(int, int)> f3 = [=](int x,int y){return f2(f1(x, y));};
  return f3;
}

函数3(操作符重载):

function<int(int)> operator()(function<int(int, int)> f1, int x)
{
  function<int(int)> f2 = [=](int y){return f1(x, y);};
  return f2;
}

当函数1和函数2(或操作符重载)时,函数3给出错误:

error: ‘std::function<int(int)> operator()(std::function<int(int, int)>, int)’ must be a nonstatic member function
     function<int(int)> operator()(function<int(int, int)> f1, int x)
                                                                    ^

为什么operator()必须是非静态成员?点(.)运算符和->在c++中?在这个问题中,答案是用指针来解释的。但这里我使用简单的operator()operator>>,这与指针无关。

这些是语言设计者决定的规则。operator()允许语法看起来像是类本身的一部分(在你的例子中是std::function),该类的接口应该由类本身控制。

标准在

中有定义

13.5.4函数调用[over.call]

1 operator()应为具有任意数量参数的非静态成员函数。[…]

强调我的

对于其他操作符,如赋值=、下标[]和类成员访问->,也做出了类似的决定,而对于像>>这样的操作符,他们认为允许在两个(几乎)任意的类之间添加操作符是有意义的,而不依赖于类的接口本身。

operator>>()可以作为非静态成员调用,也可以作为独立函数调用,这取决于如何为左侧数据类型定义它。声明:

lhs >> rhs

可以解析为:

lhs.operator>>(rhs) // non-static member

或:

operator>>(lhs, rhs) // standalone function
另一方面,

operator()不能作为独立函数调用。它的左边必须有一些东西来调用它。声明:

lhs(arguments)

只能解析为:

lhs(arguments) // only if lhs is an actual function

或:

lhs.operator()(arguments) // must be a non-static member

没有c++语言语法允许以下语句:

lhs(arguments)

解析为:

operator()(lhs, arguments)

operator>>()可以重载为非成员函数,但不能重载operator()operator()只能是classstruct的非静态成员函数。

来自标准:

13.5.4函数调用 [over.call]

1 operator()应为具有任意数目参数的非静态成员函数。它可以有默认参数。它实现了函数调用语法

,其中后缀表达式求值为一个类对象,并且表达式列表可能为空,与该类的operator()成员函数的形参列表匹配。因此,对于类型为T的类对象x,如果T::operator()(T1, T2, T3)存在并且操作符被重载解析机制(13.3.3)选为最佳匹配函数,则调用x(arg1,...)被解释为x.operator()(arg1, ...)