[英]Name for basic binary mathematic operators in C++
Is there a simple way to fill in the comments in the code below to make this work?有没有一种简单的方法可以在下面的代码中填写注释来完成这项工作?
// 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);
If it makes it easier, you may replace T
with float
.如果它更容易,您可以将T
替换为float
。
I know we can get close by using std::plus
(et al.), but that is a struct not a function, so it doesn't quite work to my knowledge.我知道我们可以通过使用std::plus
(et al.) 来接近,但这是一个结构而不是 function,所以据我所知它不太有效。
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>()) );
Here, one of the standard function objects is constructed.在这里,构造了标准 function 对象之一。 However, since they all have different types, we must explicitely cast them to a common type - std::function<float(float, float)>
.然而,由于它们都有不同的类型,我们必须明确地将它们转换为一个通用类型 - std::function<float(float, float)>
。
Lambdas maybe?也许是 Lambda?
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;});
Maybe shorter, arguably more readable code might be of interest也许更短,可以说更易读的代码可能会引起人们的兴趣
return add ? (increase ? a+b : a-b)
: (increase ? a*b : a/b);
If you need to store a callable object for later use, wrap it in a single lambda如果您需要存储可调用的 object 以供以后使用,请将其包装在单个 lambda 中
auto fun = [=](T a, T b) { return add ? (increase ? a+b : a-b)
: (increase ? a*b : a/b); };
If only following comments can be changed:如果只能更改以下注释:
auto op = add ? (increase ? /* plus */ : /* minus */)
: (increase ? /* times */ : /* divide */);
You might use lambda decaying to function pointer with +
or *
:您可以使用 lambda 衰减到 function 指针+
或*
:
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; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.