Search code examples
c++macrosvariadic-macrosboost-preprocessor

concatenate nested macro result


I have the following set of macros:

macro_1(p1)
macro_2(p1, p2)
macro_3(p1, p2, p3)
etc.

Now, I want to make another generic macro that will evaluate to the previous ones, and I am trying to do that like so:

#define macro_x(...) macro_ ## BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) (__VA_ARGS__)

The idea behind that is that BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) evaluates to the correct count of parameters, which will then turn to the correct macro.

But, unfortunately I just found out that BOOST_PP_VARIADIC_SIZE() will be evaluated after it will be concatenated to macro_, resulting in the unwanted code macro_BOOST_PP_VARIADIC_SIZE.

Is there a way I can first evaluate BOOST_PP_VARIADIC_SIZE and then concatenate to macro_?


Solution

  • This is already done for you with BOOST_PP_OVERLOAD:

    #define macro_x(...) BOOST_PP_OVERLOAD(macro_, __VA_ARGS__)(__VA_ARGS__)
    

    The reason yours doesn't work is because the concatenation needs a delay in order for the macro to expand. While easy to define your own, BOOST_PP_CAT already exists:

    #define CAT_(a, b) a##b
    #define CAT(a, b) CAT_(a, b)