为什么c++设计者选择不允许非成员operator()()
Why did the C++ designers choose not to allow non-member operator()()?
我只是在玩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()
只能是class
或struct
的非静态成员函数。
来自标准:
13.5.4函数调用 [over.call]
1
operator()
应为具有任意数目参数的非静态成员函数。它可以有默认参数。它实现了函数调用语法
,其中后缀表达式求值为一个类对象,并且表达式列表可能为空,与该类的
operator()
成员函数的形参列表匹配。因此,对于类型为T
的类对象x
,如果T::operator()(T1, T2, T3)
存在并且操作符被重载解析机制(13.3.3)选为最佳匹配函数,则调用x(arg1,...)
被解释为x.operator()(arg1, ...)
。
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 为什么 operator() 处的指针成员不起作用?
- 在单元测试中,如何在不使用 operator== 的情况下比较两个对象,这可能会错过新成员?
- 使用"operator T*()"而不是"T* operator->()"进行成员访问
- C++错误 C2801:'operator ='必须是非静态成员
- 为什么 operator[] 必须是非静态成员函数
- 如何在使用vector::operator[]迭代结构的向量时访问结构成员
- 重载Operator =作为成员函数
- 类成员operator()上的c++ typeid重载