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

时间:2012-05-03 02:01:14

标签: c++ operators switch-statement arithmetic-expressions

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

我想在c ++中做这样的事情:

int a = 1;
int b = 2;
operator op = +;
int c = a op b;
if (c == 3) // do something

由于我只考虑+-*/,我可以将运算符存储在string中,只需使用switch语句。但是我想知道是否有更好/更简单的方法。

1 个答案:

答案 0 :(得分:10)

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<>

相关问题