I sometimes want to type an expression like this:
table[row][col] = std::max(table[row][col], other_table[row+1][col+1])
(this is C++ code. Unfortunately there's no way in C++ to eliminate the duplication except by writing a helper function like void update_max(auto& a, auto const& b) { a = std::max(a, b); }
but that possibility won't be considered here)
How can I type the repeated part (table[row][col]
) quickly?
For simplicity, you may assume the expression is "simple" (you can match it with some simple regex such as .*;(.\{-})=
), but solution for the general case is okay too. (the problem is that C++ grammar is very complex)
#define replacePairMax(t,r,c,o1,o2) (t)[r][c] = std::max((t)[r][c], (t)[(r)+(o1)][(c)+(o2)])
, where the flurry of parens is to ensure complex argument expressions do not interact unexpectedly with order of operations. Usage here:replacePairMax(table, row, col, 1, 1)
.update_max
is not that bad, actually)std::
), of course we could have used other tricks (references, template functions, lambdas...). I understand OP's point: sometimes we havelhs = expression(lhs)
, andlhs
is not that simple. Instead of augmenting tracing by introducing a new function/macro that may not be used anywhere else, we just duplicate thelhs
part. Vim can be good at doing this, so, let's see how!