4 c++
例如,我可以写c:
int sum(int a, int b);
void print(int a, int b, int (*f)(int, int));
Run Code Online (Sandbox Code Playgroud)
问题是我可以发送一个运营商吗?
print(12, 13, sum);
// print(12, 13, operator +); compilation error
Run Code Online (Sandbox Code Playgroud)
Kon*_*lph 12
不幸的是,那是不可能的.在C++标准库中,functional标题中有一些常见运算符的包装器,例如std::plus<T>.但它不适用于您的代码,因为您的print函数需要特定的函数参数,plus<int>而不是.
而不是那样,尝试传递一个更好的模板参数:
template <typename BinaryFunction>
void print(int a, int b, BinaryFunction f);
print(12, 13, std::plus<int>());
Run Code Online (Sandbox Code Playgroud)