C++中基本二元数学运算符的名称

Name for basic binary mathematic operators in C++

本文关键字:运算符 二元 C++      更新时间:2023-10-16

有没有一种简单的方法来填写下面代码中的注释来使其工作?

// 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; });