借用gcc内置函数__builtin_choose_expr
和__builtin_types_compatible_p
可以帮助c来实现函数重载。
首先对这两个函数功能做下介绍
__builtin_choose_expr(expr,expr1,expr2)
与c语言:?运算符有些类似,如果expr表达式为真,那么返回expr1,否则返回expr2
_builtin_types_compatible_p(type1,type2)
测试type1与type2是否相同,如果相同返回真,否则返回假
#include <stdio.h> struct s1 { int a; int b; }; struct s2 { double a; double b; }; void over_load_s1(struct s1 s) { printf("This is over_load_s1\n"); } void over_load_s2(struct s2 s) { printf("This is over_load_s2\n"); } /*下面的宏定义主要使用了__builtin_choose_expr里嵌套了另一个__built_in_choose_expr函数 如果类型为struct s1,则返回over_load_s1的调用结果,如果类型为struct s2,则返回over_loads2的调用结果,否则显示出错信息*/ #define over_load(A)\ __builtin_choose_expr(__builtin_types_compatible_p(typeof(A), struct s1),\ over_load_s1(*(struct s1 *)&A),\ __builtin_choose_expr(__builtin_types_compatible_p(typeof(A), struct s2), \ over_load_s2(*(struct s2 *)&A),\ printf("don't support this type parameter,please check again\n"))) int main() { struct s1 s1 = {1, 2}; struct s2 s2 = {1.1, 2.2}; over_load(s1); over_load(s2); over_load(2); }
运行结果如下:
标签:load,__,gcc,函数,s2,over,重载,s1,struct From: https://www.cnblogs.com/imreW/p/17304116.html