Pass operator increment / decrement to function

I have the same function with the only difference being that it will either increase or decrease. I would like to generalize this.

template<typename O> void f(int& i, O op){ op(i); } int main() { int i; f(i,operator++); f(i,operator--); return 0; } 

How can I do this job?

my other option is to use a functional std :: plus or have two functions, but I would prefer this solution if possible. Thanks.

+5
source share
3 answers

Just use lambda:

 template<typename O> void f(int& i, O op){ op(i); } int main() { int i; f(i,[] (int& x) { ++x; }); f(i,[] (int& x) { --x; }); return 0; } 

It is also unclear whether you want a post or preincrement.

As @TC noted, if you want to preserve the semantics of a normal statement, you can add a return statement.

+6
source

Here is one option (there are many possible solutions) that also works with pre-C ++ 11:

 enum OpType { increment, decrement }; template <OpType op> void f(int &i); template<> void f<increment>(int &i) { ++i; } template<> void f<decrement>(int &i) { --i; } 

Using:

 f<increment>(i); 

To keep your code base in order, you probably want to use some scope, so either use a cloud enumeration in C ++ 11 or a namespace.

+1
source

in your case, typename O is a stateless unary function that can be modeled with a simple function pointer:

 #include <iostream> int& increment(int& i) { ++i; return i; } int& decrement(int& i) { --i; return i; } template<typename O> void f(int& i, O op){ op(i); } using namespace std; int main() { int i = 0; f(i, increment); cout << i << endl; f(i, decrement); cout << i << endl; return 0; } 

exit:

 1 0 
+1
source

Source: https://habr.com/ru/post/1209402/


All Articles