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

五迷三道 提交于 2019-12-04 12:16:32

问题


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))

and something else if it's just a single token, like this:

MY_MACRO(x)

Is that possible?

How about distinguishing between the number of space-separated tokens, i.e. between MY_MACRO(x) and MY_MACRO(x y)?

Note that I am not trying to overload based on the number of arguments - it's a unary macro in all cases.

EDIT: I am willing to use variadic macros if they help


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/5172435/overload-c-c-preprocessor-macro-on-structure-of-its-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!