Not expanding invalid branch in BOOST_CPP_IF

26 Views Asked by At

I have this macro (simplified from a real use case):

#include <boost/preprocessor.hpp>
#define MY_MACRO(x) \
    BOOST_PP_IF(BOOST_PP_IS_BEGIN_PARENS(x), \
        BOOST_PP_SEQ_ELEM(0,x),   \
        x)

It doesn't work. When passed a sequence, all is fine:

MY_MACRO((a)(b)(c)) // expands to `a`

But when passing a non-sequence, it breaks:

MY_MACRO(a) // expectation: expands to `a`
            // reality: preprocessor error

I understand why this happens. The preprocessor expands all arguments of BOOST_PP_IF. When the condition (the first argument) is false, the true branch (the second argument) is invalid. Even though the intent is to discard it, it still breaks compilation.

What is a proper way to address this problem? I could invent some homebrew macros, but surely Boost.Preprocessor should have some predefined facilities for this? I couldn't find any in the guide.

1

There are 1 best solutions below

1
n. m. could be an AI On

It looks like this transformation should work in most cases where the simplistic approach outlined above doesn't work.

Given a macro that is broken for the reason stated above:

 #define MY_MACRO(x, y, z) BOOST_PP_IF(some_condition(x, y, z), \
                                some text involving x y and z,  \
                                some other text involving x y and z)

one could rewrite it this way:

#define TRUE_BRANCH(x, y, z)   some text involving x y and z
#define FALSE_BRANCH(x, y, z)  some other text involving x y and z
#define MY_MACRO(x, y, z) \
          BOOST_PP_EXPAND(BOOST_PP_IF(some_condition(x, y, z), \
          TRUE_BRANCH, FALSE BRANCH)(x, y, z))