有没有办法让函数在 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 构造的情况下,假设我想概括此函数以接受允许我 return a-b 的运算符“-”,我有办法做到这一点吗?
我遇到了以下关于 C 的 link,我认为了解 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>());
}
您可以按照我展示的方式传递任何 these 运算符函数对象。
假设我有一个函数如下:
#include<iostream>
int func(int a, int b)
{
return a+b;
}
在不使用 if else 构造的情况下,假设我想概括此函数以接受允许我 return a-b 的运算符“-”,我有办法做到这一点吗?
我遇到了以下关于 C 的 link,我认为了解 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>());
}
您可以按照我展示的方式传递任何 these 运算符函数对象。