(对不起,我没有看到你尝试过。__attribute__
我的错)。
您可以尝试按照此处描述的“参数计数”进行试验:
http://locklessinc.com/articles/overloading/
我不知道这是否会导致 GCC 有选择地应用参数检查;但我认为应该。
更新它似乎正在工作,并添加了#define
hack:
#include <stdio.h>
int printf_1(int err)
{
printf("Got error %d\n", err);
return 0;
}
int printf_2(int error, char *string)
{
printf("Error %d and message %s\n", error, string);
return 0;
}
int printf_3(int error, char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
int printf_3(int error, char *fmt, ...)
{
printf("Received full string err=%d, fmt=%s\n", error, fmt);
return 0;
}
#define printf_4 printf_3
#define printf_5 printf_3
#define printf_6 printf_3
#define printf_7 printf_3
#define printf_8 printf_3
#define printf_9 printf_3
#define printf_10 printf_3
#define COUNT_PARMS2(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _, ...) _
#define COUNT_PARMS(...)\
COUNT_PARMS2(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define CAT(A, B) CAT2(A, B)
#define CAT2(A, B) A ## B
#define myprintf(...)\
CAT(printf_, COUNT_PARMS(__VA_ARGS__))(__VA_ARGS__)
int main()
{
myprintf(19);
myprintf(19, "Hello");
myprintf(19, "Hello '%s'", "world");
// Warning!
myprintf(19, "Hello '%s'", "world", 42);
myprintf(19, 42);
return 0;
}
我正确收到(gcc 4.6.2):
$ gcc -W -Wall -o test test.c
test.c: In function ‘main’:
test.c:48:2: warning: too many arguments for format [-Wformat-extra-args]
test.c:49:2: warning: passing argument 2 of ‘printf_2’ makes pointer from integer without a cast [enabled by default]
test.c:9:5: note: expected ‘char *’ but argument is of type ‘int’