在变量中存储基本算术运算符
Storing basic arithmetic operators in variables
如何在变量中存储基本的算术运算符?
我想在 c++ 中做这样的事情:
int a = 1;
int b = 2;
operator op = +;
int c = a op b;
if (c == 3) // do something
由于我只考虑+
、-
、*
和/
,我可以将运算符存储在string
中,只使用 switch 语句。但是我想知道是否有更好/更简单的方法。
int a = 1;
int b = 2;
std::function<int(int, int)> op = std::plus<int>();
int c = op(a, b);
if (c == 3) // do something
根据需要将std::plus<>
替换为std::minus<>
、std::multiplies<>
、std::divides<>
等。所有这些都位于标题functional
,因此请务必事先#include <functional>
。
如果您没有使用最新的编译器,请将std::function<>
替换为boost::function<>
。
相关文章:
- 函数参数变量总是需要 & 或 * 运算符吗?
- 在未初始化的变量上使用复合赋值运算符(+=, ..)不是C++中的UB?
- 如何正确返回带有成员变量的重载运算符++?
- 如何在不使用赋值运算符的情况下为动态变量赋值?
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 变量地址的运算符[]是如何工作的
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 创建变量之间的运算符排列
- C++中重载复合赋值运算符不会更改变量
- 为什么通过通用引用运算符 (&&) 将变量的引用传递给 Varadic 模板函数失败?
- 为什么 ++ 运算符触发器返回对局部变量警告的引用
- 使用运算符将分隔的输入分隔>>变量
- 不太明白 & 运算符的地址在这个结构中做什么,以及它如何能够访问其他成员变量
- 为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
- 隐藏的成员变量不应在仅允许const访问的基类中突变,以便保留分配运算符
- 将删除运算符放置在何处以进行动态变量
- 重载运算符和静态成员变量的行为
- 为什么我的重载运算符+在向自身添加变量时会在返回时使"this"未初始化?
- 需要使用 Book* 头变量重载运算符,但不起作用
- 三元运算符:编译器不发出局部变量警告的返回引用