如何使用Boost预处理程序多次打印逗号 [英] How do I print out a comma multiple times using Boost Preprocessor
问题描述
我需要使用可变宏来扩展到类的多个变体。因为他们需要根据宏输入具有不同的名称,我不能简单地使用模板。问题是,我不能扩展逗号(,
)符号,我的类有多个参数(我需要使用逗号符号)的函数。
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
提供了 BOOST_PP_COMMA()
宏到逗号,但它只在循环结构外工作。我猜这个问题是 BOOST_PP_COMMA()
被展开一次,然后被当作逗号,在这一点程序中断。
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?
推荐答案
使用 BOOST_PP_REPEAT
与可以使用预期参数调用的宏可以正常工作,甚至可以防止 BOOST_PP_COMMA
:
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) ,
要保存额外的宏,您可以利用 BOOST_PP_ENUM
在扩展之间添加逗号,方法是使用
BOOST_PP_TUPLE_EAT
:将$ 1添加到重复数中并丢弃宏参数:
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__))
我个人认为第一个更清楚。
I personally think the first is more clear.
这篇关于如何使用Boost预处理程序多次打印逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!