Overload C/C++ preprocessor macro on structure of its argument

后端 未结 2 1374
轮回少年
轮回少年 2021-02-09 18:09

I would like to write a preprocessor macro that does one thing if it\'s argument is a parenthesized tuple of tokens, like this:

MY_MACRO((x, y))
<
2条回答
  •  花落未央
    2021-02-09 18:25

    Using boost.preprocessor

    #include 
    #include 
    
    #define SEQ (w)(x)(y)(z)
    
    #define MACRO(r, data, elem) BOOST_PP_CAT(elem, data)
    
    BOOST_PP_SEQ_FOR_EACH(MACRO, _, SEQ) // expands to w_ x_ y_ z_
    

    It's not exactly the same as even a single argument case requires parenthesis. But It does allow a variable number of parenthesized arguments.

    Also a possibility: Use the BOOST_PP_IF, BOOST_PP_EQUAL, and BOOST_PP_TUPLE_ELEM to do something like:

    MACRO(1, a)
    MACRO(2, (a,b) )
    MACRO(3, (a,b,c) )
    

    or so.

提交回复
热议问题