【问题标题】:Storing basic arithmetic operators in variables将基本算术运算符存储在变量中
【发布时间】:2012-05-12 12:56:55
【问题描述】:

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

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

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

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

【问题讨论】:

  • 查看 STL 函数如何接受谓词。你可以使用std::plus之类的东西。
  • enum 是一个选项吗?字符串具体有什么问题/

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


【解决方案1】:
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&lt;&gt; 替换为std::minus&lt;&gt;std::multiplies&lt;&gt;std::divides&lt;&gt; 等。所有这些都位于标头functional,因此请务必事先#include &lt;functional&gt;

如果您没有使用最新的编译器,请将 std::function&lt;&gt; 替换为 boost::function&lt;&gt;

【讨论】:

    猜你喜欢
    • 2012-12-24
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多