C++ how to compact fancy for-loops -


if 1 lazy rewrite fancy loop on variable u, 1 can define macro this:

#define forloop(u) (int u = 0; u < n; u++) 

now, let's want this

for (int u = 0; u < n; u++) {     class& var_u = somefunctionof(u)     ... code using var_u ... } 

and let's need @ several places in code, , lazy rewrite it, because loop involves complicated conditions on multiple variables. how can compress macro ? feel annoying put 1 { in macro because whatever ide using break syntax highlighting , everything...

i had idea: define template:

template <typename loop> void forloop(int u, const loop& loop) {     (int u = 0; u < n; u++) {         class& var_u = somefunctionof(u)         loop(u, var_u);     } } 

so have write:

forloop([&](int u, class& var_u){     ... code using var_u ... }); 

i know, i'm weird. idea? inlined 100% of time? not lose performance doing instead of regular loop? performance critical in case.

other way thought about:

#define forloop(u, var_u) (int u = 0; u < n; u++) { class& var_u = somefunctionof(u) #define forloop_end } 

now call:

forloop(u, var_u) ... code using var_u ... forloop_end 

now not because {} disappeared, ide syntax checker can confused if use same variable names inside loop variables defined earlier outside of loop. thought maybe 1 can this:

forloop(u, var_u) { ... code using var_u ... } forloop_end 

but layer of { } reduces performance (even slightly)? feels 2 } mean 2 rounds of object destruction. slower destroying same set of objects in 1 round only? intuitively feels stack pointer have move twice instead of once, maybe compiler smart enough optimize that?

yes care speed , don't want loops slower regular way, feel code readability remove annoying reference initializations @ beginning of every loop in code.

thank comments , suggestions.

write index_range. write map_range.

for (auto& var_u: map_range(somefunctionof)( index_range(0,n) ) ){   ... code using var_u ... } 

compress storing map_range(somefunctionof) somewhere shared, or index range.

you never have guarantees things inlined. write clean compile-time abstract code , profile if matters.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -