tjw*_*992 8 c overloading c99 compiler-warnings c-preprocessor
我试图在C中实现函数重载,我非常接近.我正在使用C99,因此_Generic我无法使用C11中引入的关键字.我已经开发了一些工作代码,但是当我编译它时,我收到了一些警告.
工作范例:
#include <stdio.h>
#define print(x)                                                                        \
__builtin_choose_expr(__builtin_types_compatible_p(typeof(x), int   ), print_int(x)   , \
__builtin_choose_expr(__builtin_types_compatible_p(typeof(x), char[]), print_string(x), \
(void)0))
void print_int(int i) {
    printf("int: %d\n", i);
}
void print_string(char* s) {
    printf("char*: %s\n", s);
}
int main(int argc, char* argv[]) {
    print(1);
    print("this");
    return 0;
}
编译会创建以下警告:
gcc overload.c -o main
overload.c: In function 'main':
overload.c:19: warning: passing argument 1 of 'print_string' makes pointer from integer without a cast
overload.c:20: warning: passing argument 1 of 'print_int' makes integer from pointer without a cast
有关更多调试信息,以下是预处理器完成其工作后的主要功能:
int main(int argc, char* argv[]) {
 __builtin_choose_expr(__builtin_types_compatible_p(typeof(1), int ), print_int(1) , __builtin_choose_expr(__builtin_types_compatible_p(typeof(1), char[]), print_string(1), (void)0));
 __builtin_choose_expr(__builtin_types_compatible_p(typeof("this"), int ), print_int("this") , __builtin_choose_expr(__builtin_types_compatible_p(typeof("this"), char[]), print_string("this"), (void)0));
 return 0;
}
如何使编译警告消失并仍然有工作代码?
理论上,这应该工作:
#define print(x)                                                                      \
(__builtin_choose_expr(__builtin_types_compatible_p(typeof(x), int   ), print_int   , \
 __builtin_choose_expr(__builtin_types_compatible_p(typeof(x), char[]), print_string, \
(void)0))(x))
它选择print_int或者print_string,然后应用所选择的函数x.