有没有办法让函数在 c++ 中将运算符作为参数

Is there a way to make functions take in an operator as an argument in c++?

本文关键字:运算符 参数 c++ 函数 有没有      更新时间:2023-10-16

假设我有一个函数如下:

#include<iostream>
int func(int a, int b)
{
    return a+b;
}

如果不使用 if else 构造,假设我想泛化这个函数以接受允许我返回 a-b 的运算符"-",有没有办法让我这样做?

我遇到了以下关于 C 的链接,并认为知道C++中是否有任何新功能可以简化此操作是个好主意?

此外,有没有办法将运算符存储在变量中或传递对它的引用?

是的,您可以使用模板和可调用对象以有限的方式执行此操作。只需使用如下所示的模板编写函数:

#include <iostream>
template <typename T>
int func(int a, int b, T op) {
  return op(a, b);
}
// Call the function here with type.
int main() {
  std::cout << func(5, 8, std::plus<int>());
}

您可以按照我展示的方式传递这些运算符函数对象中的任何一个。