void cpp_overload1(int p1)
{
printf("CPP One param: %d\n", p1);
}
void cpp_overload2(double *p1, const char *p2)
{
printf("CPP Two params: %p (%f) %s\n", p1, *p1, p2);
}
void cpp_overload3(int p1, int p2, int p3)
{
printf("CPP Three params: %c %d %d\n", p1, p2, p3);
}
#define CAT(A, B) CAT2(A, B)
#define CAT2(A, B) A ## B
#define cpp_overload(...)\
CAT(cpp_overload, COUNT_PARMS(__VA_ARGS__))(__VA_ARGS__)
3、根据 "函数指针" 实现重载
typedef struct _int_param {
int param1;
int param2;
}INT_PARAM;
typedef struct _double_param_ {
double param1;
double param2;
}DOUBLE_PARAM;
typedef void* (*ADDFUNC)(void*);
void* int_add_func(void* wParam)
{
INT_PARAM* lParam = (INT_PARAM*)wParam;
int res = lParam->param1 + lParam->param2;
return (void*)&res;
}
void* double_add_func(void* wParam)
{
DOUBLE_PARAM* lParam = (DOUBLE_PARAM*)wParam;
double res = lParam->param1 + lParam->param2;
return (void*)&res;
}
void* add_func(ADDFUNC f, void* wParam)
{
return f(wParam);
}
int test()
{
INT_PARAM val1 = {10, 20};
DOUBLE_PARAM val2 = {30.5, 40.5};
void* res1 =
add_func(int_add_func, &val1);
int result1 = *((int*)res1);
void* res2 = add_func(double_add_func, &val2);
double result2 = *((double*)res2);
return 0;
}
4、根据 "gcc内置函数" 实现重载
__builtin_types_compatible_p() __builtin_choose_expr()
void gcc_type_overload_aux(int typeval, ...)
{
switch(typeval)
{
case 1:
{
va_list v;
va_start(v, typeval);
struct s1 s = va_arg(v, struct s1);
va_end(v);
gcc_overload_s1(s);
break;
}
case 2:
{
va_list v;
va_start(v, typeval);
struct s2 s = va_arg(v, struct s2);
va_end(v);
gcc_overload_s2(s);
break;
}
default:
{
printf("Invalid type to 'gcc_type_overload()'\n");
exit(1);
}
}
}
#define gcc_type_overload(A)\
gcc_type_overload_aux(\
__builtin_types_compatible_p(typeof(A), struct s1) * 1\
+ __builtin_types_compatible_p(typeof(A), struct s2) * 2\
, A)