c++ - 为什么 C++ 设计者选择不允许非成员运算符 ()()?

标签 c++ c++11 gcc g++ c++14

我只是在玩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/

相关文章:

c++ - C++ 中的无符号整数 for 循环

python - 嵌入式 python 在导入 matplotlib.pyplot 时崩溃

c++ - 返回没有 std::function 的 lambda

c++ - 程序员的错误或 gcc-5.1.0 的错误?

gcc - 如何链接到 gcc 中的 libatomic 库

c++ - 如何有条件地为 Eclipse 中的交叉编译项目包含两个相同版本的不同名称的库?

c++ - 这个异步技巧会起作用还是当我访问它时状态会悬空?

c++ - 尝试从 OpenGL 创建 OpenCL 上下文时出现无效共享组错误

c++ - 你觉得这个 for 循环宏怎么样?

c++ - Qt 5.1 for OSX 安装仅包含 clang_64 目录,如何使用 macports gcc 进行编译?