c++ - 我可以将运算符作为参数发送给函数吗?

标签 c++

例如我可以用c写:

int sum(int a, int b);
void print(int a, int b, int (*f)(int, int));

问题是我可以派接线员吗?

print(12, 13, sum);
// print(12, 13, operator +); compilation error

最佳答案

很遗憾,这是不可能的。 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>());

关于c++ - 我可以将运算符作为参数发送给函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1448641/

相关文章:

c++ - 梳状排序在 C++ 中不起作用

c++ - ifstream 不从 C++ 文件中读取值

c++ - 如何在 clang(或 gcc)中删除 C++ 名称?

c++ - 对象的引用计数通常存储在哪里?

c++ - boost::multiprecision::float128 和 C++11

c++ - C++中的引导加载程序

c++ - 单击更改字体颜色

c++ - 时间多数表决算法错误

C++ c2664 错误 "cannot convert argument 1 from std::string to _Elem *"

c++ - ZLIB解压缩