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

后端 未结 2 1370
轮回少年
轮回少年 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:24

    As for your first question, the following macros might meet your purpose:

    #define CONCAT_( x, y ) x ## y
    #define CONCAT( x, y ) CONCAT_( x, y )
    #define IS_SINGLE_1(...) 0
    #define IGNORE(...)
    #define IS_SINGLE_2_0           0 IGNORE(
    #define IS_SINGLE_2_IS_SINGLE_1 1 IGNORE(
    #define IS_SINGLE( x ) CONCAT( IS_SINGLE_2_, IS_SINGLE_1 x ) )
    IS_SINGLE((x, y)) // 0
    IS_SINGLE(x)      // 1
    

    Macro IS_SINGLE is expanded to 1 if the argument is single token, otherwise, 0.

    Hope this helps

    0 讨论(0)
  • 2021-02-09 18:25

    Using boost.preprocessor

    #include <boost/preprocessor/cat.hpp>
    #include <boost/preprocessor/seq/for_each.hpp>
    
    #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.

    0 讨论(0)
提交回复
热议问题