Search code examples
cc-preprocessorc99variadic-macros

reverse the arguments to a variadic macro


How do I reverse the arguments to a variadic macro? For example, I'd like

#define REVERSE(...) ???

REVERSE(A,B,C) // expands to C,B,A

My goal is to separate the front and back arguments:

#define APPLY(FUN,...) FUN(__VA_ARGS__)

#define FRONT(FIRST,...) FIRST
#define REST(FIRST,...) __VA_ARGS__
#define MOST(...) APPLY(REVERSE,APPLY(REST,REVERSE(__VA_ARGS__)))
#define BACK(...) APPLY(FRONT,REVERSE_ARGUMENTS(__VA_ARGS__))

FRONT(A,B,C) // expands to A
REST(A,B,C) // expands to B,C
MOST(A,B,C) // expands to A,B
BACK(A,B,C) // expands to C

Solution

  • The Boost Preprocessor Library can reverse macro arguments. Unfortunately, it only works up to an implementation-defined maximum argument list length. As far as I can tell, it is not possible to write a macro that reverses an arbitrarily long list of arguments.

    #include <boost/preprocessor.hpp>
    
    #define REVERSE(...) BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_REVERSE(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)))
    
    #define APPLY(FUN,...) FUN(__VA_ARGS__)
    
    #define FRONT(FIRST,...) FIRST
    #define BACK(...) APPLY(FRONT,REVERSE(__VA_ARGS__))
    #define REST(FIRST,...) __VA_ARGS__
    #define MOST(...) APPLY(REVERSE,APPLY(REST,REVERSE(__VA_ARGS__)))