MrD*_*ase 7 c++ arithmetic-expressions operators switch-statement
如何在变量中存储基本算术运算符?
我想在c ++中做这样的事情:
int a = 1;
int b = 2;
operator op = +;
int c = a op b;
if (c == 3) // do something
Run Code Online (Sandbox Code Playgroud)
由于我只考虑+,-,*而且/我可以在运营商存储在string,只是使用switch语句.但是我想知道是否有更好/更简单的方法.
ild*_*arn 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
Run Code Online (Sandbox Code Playgroud)
更换std::plus<>用std::minus<>,std::multiplies<>,std::divides<>等,如需要的话.所有这些都位于标题中functional,所以一定要#include <functional>事先确定.
更换std::function<>用boost::function<>,如果你没有使用最新的编译器.
| 归档时间: |
|
| 查看次数: |
6223 次 |
| 最近记录: |