繁体   English   中英

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 (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>()) );

在这里,构造了标准 function 对象之一。 然而,由于它们都有不同的类型,我们必须明确地将它们转换为一个通用类型 - std::function<float(float, float)>

也许是 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;});

也许更短,可以说更易读的代码可能会引起人们的兴趣

return add ? (increase ? a+b : a-b)
          : (increase ? a*b : a/b);

如果您需要存储可调用的 object 以供以后使用,请将其包装在单个 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 衰减到 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM