假设我有一个功能
#include <iostream>
int do_math (num_1, num_2, "*"){
....
}
Run Code Online (Sandbox Code Playgroud)
代码获取输入并在函数中应用运算符以获得计算结果。
我不确定如何在函数中加入算术运算符来进行计算。我正在考虑使用 ASCII 表中的运算符值,但我希望也许我可以以某种方式合并 istringstream 方法来做到这一点。有什么建议?
也可以通过模板来完成
template<typename Input, typename BinaryOp>
auto do_math(Input a, Input b, BinaryOp op)
{
return op(a,b);
}
Run Code Online (Sandbox Code Playgroud)
这可以这样调用:
auto res = do_math(5, 4, std::plus<int>());
Run Code Online (Sandbox Code Playgroud)