编辑------------------------------------------------看这里 - - - - - - - - - - - - - - - - - - - - - - - - - ---------------->
(根据参数数量重载宏)
// functions, or macros, ....
void bar(){}
void bar(int){}
#define EXPAND(X) X // for MSVC10 compatibility
// compute number of (variadic) macro arguments
// from http://groups.google.com/group/comp.std.c/browse_thread/thread/77ee8c8f92e4a3fb/346fc464319b1ee5?pli=1
#define PP_NARG(...) EXPAND( PP_NARG_(__VA_ARGS__, PP_RSEQ_N()) )
#define PP_NARG_(...) EXPAND( PP_ARG_N(__VA_ARGS__) )
#define PP_ARG_N(_1, _2, _3, N, ...) N
#define PP_RSEQ_N() 3, 2, 1, 0
// macro for exactly 2 arguments
#define FOO_2(_1, _2) bar()
// macro for exactly 3 arguments
#define FOO_3(_1, _2, _3) bar(_2)
// macro selection by number of arguments
#define FOO_(N) FOO_##N
#define FOO_EVAL(N) FOO_(N)
#define FOO(...) EXPAND( FOO_EVAL(EXPAND( PP_NARG(__VA_ARGS__) ))(__VA_ARGS__) )
int main()
{
int something = 42;
FOO("daf", sfdas);
FOO("fdsfs", something, 5);
}
预处理器输出:
void bar(){}
void bar(int){}
int main()
{
int something = 42;
bar();
bar(something);
}
Edit2:似乎 VS2010 有一些问题__VA_ARGS__
和宏替换。
更新:这是......一个错误? (另见这个问题):
#define MACRO2(PARAM0, PARAM1, ...) arg 0: >PARAM0< arg 1: >PARAM1< \
additional args: >__VA_ARGS__<
#define MACRO1(...) MACRO2(__VA_ARGS__, OTHERARG_0, OTHERARG_1)
MACRO1(ARG0, ARG1);
预处理器输出:
arg 0: >ARG0, ARG1< arg 1: >OTHERARG_0< additional args: >OTHERARG_1<;
有关解决方法,请参阅链接的 SO 问题。我已经更新了上面的原始答案(代码)并使用 MSVC10 对其进行了测试 -> 现在可以工作。