Choosing regular arithmetic operation as function of boolean

Is it possible to make something like this:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

using namespace std;

int main(void) {
    int (*z[2]) (int) = {&(operator-), &(operator+)};
    bool add = true;
    cout<<(3.*z[add])(8);
    return 0;
}


Basically, I want to choose addition if add equals true and subtraction otherwise, without having to rely on creating structs, functions or switches, because it makes for less code. Is this possible?
Last edited on
Does this meet your requirements? I think std::function is easier than directly dealing with function pointers, but you should be able to turn it into a raw function pointer array if you need to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <functional>

int main()
{    
    std::function<int(int, int)> ops[2] {
        std::minus<int>(),
        std::plus<int>()
    };
    
    bool add = true;
    std::cout << ops[add](3, 8) << "\n";
    
    add = false; // subtract
    std::cout << ops[add](3, 8) << "\n";
    
    return 0;
}


http://en.cppreference.com/w/cpp/utility/functional/plus
http://en.cppreference.com/w/cpp/utility/functional/minus

Edit: Actually, I'm not sure of a "nice" way to make it work with raw pointers, but I bet something exists. But really, std::function has much nicer syntax.
Last edited on
I didn't know that the standard library had function wrappers defined for addition and subtraction. That was exactly what I was looking for. Some compilers (like the latest version of Xcode) seem to have these functions integrated in iostream, making the functional include unnecessary. One can make it work with raw pointers by implementing their own addition/subtraction functions and then pointing to those functions.
Last edited on
Well, you should still put the <functional> in there for portability. And extra little include line shouldn't break a design :)

But yeah it has those built-in, otherwise you'd have to define a lambda or something, not sure.

One can make it work with raw pointers by implementing their own addition/subtraction functions and then pointing to those functions.

True! But that violated your original requirement :p
Last edited on
Topic archived. No new replies allowed.