How to make #if #endif part of a macro

#define M(N)\
#if N == 5\
    /*several lines of code that 
      Can't be replaced with a   
      tertnary operator*/
#else\
    N;\
#endif

When I use this macro in this way

M(5);

I expect the conclusion to be

// everything within the #if #else block

But it does not compile.

I am not surprised that it does not compile: I know that #if cannot be used in the continuation line, that is, "\".

I also tried

#define POUND_IF #if

And then use POUND_IF, but not working.

Can this be done?

Is there any great material for the Boost pre-processor that can be used?

+4
source share
2 answers

In a compressed form you cannot. Instead, you can rely on the optimizer:

#define M(N)\
    do { if (N == 5) { \
    /*several lines of code that 
      Can't be replaced with a   
      ternary operator*/ \
    } else { N; } } while (0)

, N 5 (, M(5)), if . , N 5, , else. , , , .

+6

(, #).

, . :

#define ONE_OR_TWO(...) ONE_OR_TWO_(__VA_ARGS__, 2, 1,)
#define ONE_OR_TWO_(_1, _2, X, ...) X
#define CAT(A, B) CAT_(A, B)
#define CAT_(A, B) A ## B

#define M(N) CAT(IF_, ONE_OR_TWO(CAT(IS_, N)))({\
    code; \
    code; \
}, N)
#define IS_5 ,
#define IF_1(A, B) B
#define IF_2(A, B) A

M(5);  //-> { code; code; }
M(8);  //-> 8

. M, , , , - (, - , , , ).

. , , . , , Order-PP Boost.Preprocessor, , .

+5

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


All Articles