How do I print out a comma multiple times using Boost Preprocessor

依然范特西╮ 提交于 2019-12-12 23:05:09

问题


I need to use a variadic macro to expand to multiple variations of a class. Since they need to have different names based on the macro input I can't simply use templates. The problem is that I can't expand the comma (,) symbol, and my class has functions which take multiple parameters (for which I need to use the comma symbol).

boost provides the BOOST_PP_COMMA() macro which expands to a comma, but it only works outside of loop constructs. I'm guessing the issue is that BOOST_PP_COMMA() is expanded once and then treated as a comma, at which point the program breaks.

To illustrate the problem, suppose I have a macro function which takes a variadic number of parameters and produces a number of commas equal to the number of parameters given to it. The naive solution would be this:

#define TEST(...)\
    BOOST_PP_REPEAT( \
        BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
        MACRO, \
        BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__))

#define MACRO(z, n, data) BOOST_PP_IF(1,BOOST_PP_COMMA(),BOOST_PP_COMMA())\

But this produces a range of errors because the comma is expanded and the macro thinks they're dividing parameters.

Is there any way around this problem?


回答1:


Using BOOST_PP_REPEAT with a macro that can be called with the expected arguments will work fine, and it even prevents the need for BOOST_PP_COMMA:

#define PRINT_COMMAS(...)\
    BOOST_PP_REPEAT( \
        BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
        PRINT_COMMAS_MACRO, \
        BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__))

#define PRINT_COMMAS_MACRO(z, n, data) ,

See it work

To save the extra macro, you can take advantage of the fact that BOOST_PP_ENUM adds commas between expansions by adding one to the number of repetitions and discarding the macro arguments using BOOST_PP_TUPLE_EAT:

#define PRINT_COMMAS(...)\
    BOOST_PP_ENUM( \
        BOOST_PP_INC(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__)), \
        BOOST_PP_TUPLE_EAT(), \
        BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__))

See it work

I personally think the first is more clear.



来源:https://stackoverflow.com/questions/24770397/how-do-i-print-out-a-comma-multiple-times-using-boost-preprocessor

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