我只是在玩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()
需要是非静态成员?
我认为它不同于 What is the difference between the dot (.) operator and -> in C++?在那个问题中,答案是用指针来解释的。但在这里我使用简单的 operator()
和 operator>>
,这与指针无关。
最佳答案
这些是语言设计者决定的规则。 operator()
允许一种看起来像是类本身的一部分的语法(在您的情况下为 std::function
)并且该类的接口(interface)应该由类本身。
标准在
中定义了这个13.5.4 Function call [over.call]
1
operator()
shall be a non-static member function with an arbitrary number of parameters. [...]
强调我的
对于赋值 =
、下标 []
和类成员访问 ->
等其他运算符也做出了类似的决定,而像 >>
,他们认为允许在两个(几乎)任意类之间独立于类的接口(interface)本身添加运算符是有意义的。
关于c++ - 为什么 C++ 设计者选择不允许非成员运算符 ()()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409287/