Home > database >  Dynamic macro-selection in a loop
Dynamic macro-selection in a loop

Time:06-22

I have a header file 'a.h' with some macro-definitions of the type:

Header 'a.h' contents:

#define STREAM1 cout
#define STREAM2 cerr
#define STREAM3 some_out_stream3
#define STREAM4 some_out_stream4
...
#define STREAM100 some_out_stream100

Now in a different c file which includes the above header, I need to use the above macros, in the following way.

STREAM1 << some_text_method( 1 );
STREAM2 << some_text_method( 2 );
...
STREAM100 << some_text_method( 100 );

Is there a way, possibly by macro or function definition, to do the above in a loop:

int i;
for(i = 1; i <= 100; i  )
    SOME_MACRO_OR_METHOD( i );

CodePudding user response:

Put all the macros in an array and loop over them.

std::ostream streams[] = {STREAM1, STREAM2, ...STREAM100};

for (int i = 0; i < std::size(streams); i  ) {
    streams[i] << some_text_method(i 1);
}
  • Related