在变量中存储基本算术运算符

Storing basic arithmetic operators in variables

本文关键字:运算符 变量 存储      更新时间:2023-10-16

如何在变量中存储基本的算术运算符?

我想在 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<>

相关文章: