简体   繁体   中英

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 .


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.

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. However, since they all have different types, we must explicitely cast them to a common type - std::function<float(float, float)> .

Lambdas maybe?

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

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 * :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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