I have the same function with the only difference that it will either increment or decrement. I would like to generalize from that.
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 make this work?
my other option is to use functional std::plus or have two functions but I'd prefer this solution if possible. Thank you.
Increment ++ and Decrement -- Operator as Prefix and Postfix In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1. Simple enough till now.
In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.
2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement. Example int i = 3; int a = i++; // a = 3, i = 4 int b = ++a; // b = 4, a = 4. Example 1. Java.
++i is sometimes faster than, and is never slower than, i++. For intrinsic types like int, it doesn't matter: ++i and i++ are the same speed. For class types like iterators or the previous FAQ's Number class, ++i very well might be faster than i++ since the latter might make a copy of the this object.
Simply use a 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;
}
Also it is not clear whether you want post- or preincrement.
As noted by @T.C. if you want to keep the semantics of the normal operator you can add the return statement.
Here is one option (there are many possible solutions) that also works 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; }
Usage:
f<increment>(i);
To keep your codebase tidy you probably want to use some scoping though, so either use a scoped enum in C++11, or a namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With