C++中基本二元数学运算符的名称
Name for basic binary mathematic operators in C++
有没有一种简单的方法来填写下面代码中的注释来使其工作?
// Assuming the following definitions already...
T a, b;
bool add, increase;
// ...can we fill in the comments here so result is computed as desired?
auto op = add ? (increase ? /* plus */ : /* minus */)
: (increase ? /* times */ : /* divide */);
T result = op(a, b);
如果它更容易,您可以将T
替换为float
.
我知道我们可以通过使用std::plus
(等人(来接近,但这是一个结构而不是一个函数,所以据我所知,它不太有效。
using F = std::function<float(float, float)>;
auto op = add ? (increase ? F(std::plus<float>()) : F(std::minus<float>()) )
: (increase ? F(std::multiplies<float>()) : F(std::divides<float>()) );
这里构造了一个标准函数对象。但是,由于它们都有不同的类型,我们必须将它们明确转换为通用类型 -std::function<float(float, float)>
。
也许是Lambdas?
auto op = add ? (increase ? [](float a, float b) {return a+b;} : [](float a, float b) {return a-b;})
: (increase ? [](float a, float b) {return a*b;} : [](float a, float b) {return a/b;});
也许更短,可以说更具可读性的代码可能会引起人们的兴趣
return add ? (increase ? a+b : a-b)
: (increase ? a*b : a/b);
如果您需要存储可调用对象以供以后使用,请将其包装在单个 lambda 中
auto fun = [=](T a, T b) { return add ? (increase ? a+b : a-b)
: (increase ? a*b : a/b); };
如果只能更改以下注释:
auto op = add ? (increase ? /* plus */ : /* minus */)
: (increase ? /* times */ : /* divide */);
您可以使用 lambda 衰减来函数指针,+
或*
:
auto op = add ? (increase ? +[](const T& lhs, const T& rhs) { return lhs + rhs; }
: +[](const T& lhs, const T& rhs) { return lhs - rhs; })
: (increase ? +[](const T& lhs, const T& rhs) { return lhs * rhs; }
: +[](const T& lhs, const T& rhs) { return lhs / rhs; });
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 重写派生类中的二元运算符
- 最小值/最大值二元运算符
- C++中基本二元数学运算符的名称
- 二元运算符声明的'static'关键字
- 二元运算符"<<"不能应用于类型 "wostream" 和 "string" 的表达式
- 重载二元运算符的右操作数是否可以是基本类型的对象
- 如何返回重载二元运算符的值
- 后缀运算符不应该被视为二元运算符吗
- 二元运算符重载,隐式类型转换
- 二元运算符 + , = 使用常量重载
- 二元运算符重载和多晶种
- c++中重载二元关系运算符的正确方法
- 如何用二元运算符的比较结果来解释条件
- 错误:重载的"运算符<<"必须是二元运算符(有 3 个参数)