There is no post-fix increment operator by a step other than 1. The obj += 2
expression returns the new value, rather than the old.
If obj is a class, you could hack your +=
operator overload to return the old value, but it would be a bad idea.
What we can do is make a simple template function called postinc
which does this for us in a type generic way:
#include <iostream>
template <typename OBJ, typename DELTA>
OBJ postinc(OBJ &obj, const DELTA &delta)
{
OBJ oldval = obj;
obj += delta;
return oldval;
}
using std::cout;
using std::endl;
int main()
{
int x = 39;
int y = postinc(x, 3); // <-- now we can do this
// x and 3 can be any objects supporting x += 3
cout << "x = " << x << "; y = " << y << endl;
return 0;
}
Output:
x = 42; y = 39
As you can see, y
received the old value of x
, and x
incremented by 2
.
All we did was y = postinc(x, 2)
. It's not fancy syntactic sugar like a post-incrementing overload of y += 2
, but it does the job of sitting nicely in an expression, eliminating a clumsy breakup of the code to introduce temporary variables.
If you don't need postfix semantics, or even the result value of the expression at all, then just use var += delta
.