有没有办法让函数在 c++ 中将运算符作为参数
Is there a way to make functions take in an operator as an argument in c++?
假设我有一个函数如下:
#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>());
}
您可以按照我展示的方式传递这些运算符函数对象中的任何一个。
相关文章:
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- 运算符重载:"operator+"必须采用零个或一个参数
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 参数相关查找和流运算符重载
- C++:使用运算符 = 调用多参数构造函数
- 了解布尔运算符==(参数 1,参数 2)
- 我能否根据其运算符()的签名专门化可变参数模板参数
- SFINAE 检查模板参数运算符
- 不允许运算符 const 参数调用 const 成员函数
- 为私有结构定义双参数运算符重载
- C++ 通过自定义赋值运算符隐式转换函数参数
- 函数参数变量总是需要 & 或 * 运算符吗?
- 算术运算符参数类型
- 隐式转换以匹配运算符参数
- 对重载运算符参数执行隐式转换时出现编译器错误
- 避免在C++中强制转换运算符参数
- 如果给定模板不是运算符参数类型的专用模板,则禁用运算符重载
- 以及C++中的运算符参数求值
- 这个函数的运算符参数太多