Search code examples
c++macrosheader-files

How to repeat code using __VA_ARGS__ in c++?


I want to create a macro in C++ that does the following.

#define SETUP_BULK(...) \
SETUP_HELPER(__VA_ARG__) \ // repeat this for all __VA_ARGS__

Is this possible? I looked up other questions on iterating __VA_ARGS__ but to no avail.

I can't use anything other than macros, or that would defeat the purpose of my goal - to dynamically setup structures with my custom JSON parser.

Eg:

SETUP_BULK(Struct_A, Struct_B, Struct_C)

would turn into

SETUP_HELPER(Struct_A);
SETUP_HELPER(Struct_B);
SETUP_HELPER(Struct_C);

Solution

  • If you insist on doing this at the level of macros, the simplest solution is to use Boost.Preprocessor:

    #include <boost/preprocessor/variadic/to_seq.hpp>
    #include <boost/preprocessor/seq/for_each.hpp>
    
    // ...
    
    #define SETUP_HELPER2(r, data, elem) SETUP_HELPER(elem)
    
    #define SETUP_BULK(...) \
    BOOST_PP_SEQ_FOR_EACH(SETUP_HELPER2, _, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))
    

    Demo