Search code examples
boostmacrosc-preprocessorboost-preprocessor

Macro resulting from evaluation of other macros not evaluated


I have a question about the way C preprocessor works. I've written the code below. When OPREP(n) is used it should result in something like this: OP(0,OP(1,OP(2,OP(3, .... OP(n,. Then what I wanted to achieve is when I add something like whatever))))))) with n right parentheses, I should get OP(0,OP(1,OP(2,OP(3, .... OP(n,whatever))))))) which should evaluate to 0 1 2 3 4 5 .... n whatever.

#include <boost/preprocessor/comma.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/punctuation/paren.hpp>

#define OP(a,b) a b
#define T0() OP
#define OPMAC(z,n,s) T0()BOOST_PP_LPAREN() n BOOST_PP_COMMA()
#define OPREP(n_) BOOST_PP_REPEAT(n_, OPMAC, a)

OPREP(2) 3))

When I compile and look at the preprocessor output I get: OP( 0 , OP( 1 , 3)). That is it didn't evaluate the resulting OP() macros. My question is why, and how can I force it to be evaluated?


Solution

  • I figured it out. To force another evaluation all I need to do is add a dummy FORCE_EVAL macro that evaluates to the same thing as its parameters and enclose my call in it:

    #include <boost/preprocessor/comma.hpp>
    #include <boost/preprocessor/repetition/repeat.hpp>
    #include <boost/preprocessor/punctuation/paren.hpp>
    
    #define OP(a,b) a b
    #define T0() OP
    #define OPMAC(z,n,s) T0()BOOST_PP_LPAREN() n BOOST_PP_COMMA()
    #define OPREP(n_) BOOST_PP_REPEAT(n_, OPMAC, a)
    #define FORCE_EVAL(...) __VA_ARGS__
    
    FORCE_EVAL(OPREP(2) 3)))