How much can you do with macros (higher order)?

Is it "safe" to give macro names as arguments to other macros to simulate higher-order functions?

those. where should I look so as not to shoot in the leg?

Here are some snippets:

#define foreach_even(ii, instr) for(int ii = 0; ii < 100; ii += 2) { instr; }
#define foreach_odd(ii, instr)  for(int ii = 1; ii < 100; ii += 2) { instr; }

#define sum(foreach_loop, accu) \
  foreach_loop(ii, {accu += ii});

int acc = 0;
sum(foreach_even, acc);
sum(foreach_odd, acc);

How about a partial application, can I do this?

#define foreach(ii, start, end, step, instr) \
  for(int ii = start; ii < end; ii += step) { instr; }

#define foreach_even(ii, instr) foreach(ii, 0, 100, instr)
#define foreach_odd(ii, instr)  foreach(ii, 1, 100, instr)

#define sum(foreach_loop, accu) \
  foreach_loop(ii, {accu += ii});

int acc = 0;
sum(foreach_even, acc);
sum(foreach_odd, acc);

And can I define a macro inside a macro?

#define apply_first(new_macro, macro, arg) #define new_macro(x) macro(arg,x)
+3
source share
2 answers

If you use as much preprocessor as possible, you can try boost.preprocessor .

, . , , . , ( ) - , .

: " ", " ".

+3

c-. , - .

"" . . - , - .

, . , ... gcc ,

nested_macro.cc:8: : '#'
nested_macro.cc:3: : , '('
nested_macro.cc:3: : '}'

. , https://sourceforge.net/projects/dut/

+1

Source: https://habr.com/ru/post/1707773/


All Articles