在C或C ++中使用逗号作为宏名称 [英] Using comma as macro name in C or C++
问题描述
我想做以下事情:
#define ,
#define MAX 10,000,000
// ...
#undef ,
有什么窍门吗?
编辑:我知道C ++ 14中'
的数字分隔符。我正在寻找一种对不兼容的编译器执行相同操作的技巧。
编辑2:请考虑 Variadic宏
。
I know about the '
digit separator in C++14. I'm looking for a trick to do the same for uncompliant compilers.
Please consider Variadic Macros
.
推荐答案
警告,黑魔法即将来临。
Warning, black magic ahead.
确实可以使用宏,尽管预设数量为论点。该数字可以是任意的,但每个数字都必须用手写的:
Macros can indeed be used, albeit with a preset number of arguments. This number can be arbitrary, but each must be written by hand:
#include <stdio.h>
#include <stdlib.h>
#define MERGE_EXPAND( a , b ) a##b
#define MERGE( a , b ) MERGE_EXPAND( a , b )
#define COUNT_PICK( a , b , c , pick , ... ) pick
#define COUNT( ... ) COUNT_PICK( __VA_ARGS__ , 3 , 2 , 1 , 0 )
#define JOIN_1( a ) a
#define JOIN_2( a , b ) a##b
#define JOIN_3( a , b , c ) a##b##c
#define JOIN( ... ) MERGE( JOIN_ , COUNT( __VA_ARGS__ ) )( __VA_ARGS__ )
int main( void )
{
printf( "%d\n" , JOIN( 12345 ) ) ;
printf( "%d\n" , JOIN( 100,44 ) ) ;
printf( "%d\n" , JOIN( -10,44,9999 ) ) ;
return EXIT_SUCCESS ;
}
宏COUNT计算传递给它的参数数量。这是通过将参数传递给辅助宏COUNT_PICK并添加其他参数(它们是相反顺序的连续数字)来完成的。然后,传递给COUNT的原始参数数将操纵COUNT_PICK的参数,因此将选择其中一个数字。
The macro COUNT count the number of arguments passed to it. This is done by passing arguments to the helper macro COUNT_PICK, and adding additional argument which are consecutive numbers in reverse order. The number of original arguments passed to COUNT then manipulates the arguments of COUNT_PICK, so that one of the numbers is chosen.
然后将所选的数字与JOIN合并,从而得到JOIN_1,JOIN_2或JOIN_3。然后将选定的宏与原始参数一起使用,并将它们简单地合并为一个整数文字。
That chosen number is then merged wtih JOIN, resulting in either JOIN_1, JOIN_2, or JOIN_3. The chosen macro is then used with original arguments and simply merges them into a single integer literal.
可以通过手动定义更多的JOIN_X宏(其中X是连续的)来扩展此示例数。同时必须更改宏COUNT和COUNT_PICK。
This example can be expanded by manually defining more JOIN_X macros where X is a consecutive number. Simultaneously the macros COUNT and COUNT_PICK, must be altered as well.
另一个好处是,传递无效参数,例如:
As an additional benefit, passing invalid arguments, like:
JOIN( 10,+44 );
JOIN( 10,-44 );
JOIN( 10,*44 );
JOIN( 10,/44 );
JOIN( /10,44 );
//etc...
会产生编译时间警告,但仍然允许将导致有效整数常量的参数。
will yield a compile time warning, but still allows for arguments that will result in a valid integer constant.
要与经过SVC14(Microsoft Visual Studio 2015 Update 3)测试的Microsoft编译器一起使用,必须对代码进行修改。 COUNT_PICK和MERGE宏必须使用其他扩展宏进行包装:
To be used with a Microsoft compiler, tested with SVC14 (Microsoft Visual Studio 2015 Update 3), the code must be amended. Macros COUNT_PICK and MERGE must be wrapped with an additional expand macro:
#define EXPAND(...) __VA_ARGS__
这篇关于在C或C ++中使用逗号作为宏名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!