且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以传递一个括号括起来的初始化程序作为宏参数?

更新时间:2022-03-13 20:57:10

您可以使用

#define MYMACRO(T,...) literal<T>(__VA_ARGS__);

如果您有更多参数,可以使用间接:

In case you have more parameters, you can use an indirection:

#define UNWRAP(...) __VA_ARGS__
#define MYMACRO(T,A) literal<T>(UNWRAP A);

现在您可以使用

MYMACRO( long[2], ({1, 2}) )





更新的答案

您也可以根据需要更换大括号调用具有圆括号的宏:

You could also, if you like, replace the curly brackets in the invocation of the macro with the round brackets:

#define BRACED_INIT_LIST(...) {__VA_ARGS__}
#define MYMACRO(T,A) literal<T>(BRACED_INIT_LIST A);

并致电

MYMACRO( long[2], (1, 2) )

与典型的宏调用风格一致。

which is IMHO consistent with typical macro-invocation-styles.

在你的其他问题上的一些话:预处理器不了解语言(C,C ++,C ++ 11)不应该关心符号的特殊意义。它跟踪圆括号,但几乎所有的东西只是令牌。

Some words on your other questions: The preprocessor knows nothing about the language (C, C++, C++11) and hence should not care about the special meaning of symbols. It is tracking round brackets, but almost everything else is just tokens.

我也认为这不是标准委员会的监督,因为重点应该是使用在大多数情况下预处理器是多余的。您是否考虑过其他(非宏)技术来实现 MYMACRO ?另外,剩下的使用情况(如上所示)的解决方法当然是可能的。

I also think it's not an oversight from the standard committee as the focus should be on making the use of the preprocessor superfluous for most cases. Have you considered other (non-macro) techniques to implement MYMACRO? Also, work-arounds for the remaining use-cases (as shown above) are certainly possible.

最后,它肯定不是GCC中的错误,因为编译器只是实现标准是什么。

Finally, it is certainly not a bug in GCC as the compiler simply implements what the standard says.