Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing increment/decrement operator to a function

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.

like image 911
kirill_igum Avatar asked Dec 17 '14 21:12

kirill_igum


People also ask

How do you use increment and decrement operator?

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.

Can I put ++ i ++ in C?

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.

What is i ++ and ++ i explain with an example?

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.

Is ++ i or i ++ more efficient?

++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.


2 Answers

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.

like image 59
Stephan Dollberg Avatar answered Nov 12 '22 20:11

Stephan Dollberg


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.

like image 42
M.M Avatar answered Nov 12 '22 21:11

M.M