我想在C语言中编写一些函数,但它们必须适用于所有数字类型(int、float、double)。那么什么是最佳实践?使用void指针(当然还有函数指针)?还是为每种类型编写不同的函数?
例如:
float func(float a, float b) {
return a+b;
}
我想在C语言中编写一些函数,但它们必须适用于所有数字类型(int、float、double)。那么什么是最佳实践?使用void指针(当然还有函数指针)?还是为每种类型编写不同的函数?
例如:
float func(float a, float b) {
return a+b;
}
#include <stdio.h>
int ifunc(int a, int b) { return a+b; }
float ffunc(float a, float b) { return a+b; }
double dfunc(double a, double b) { return a+b; }
#define func(x, y) \
_Generic((x), int: ifunc, float: ffunc, double: dfunc, default: ifunc)(x, y)
int main(void)
{
{
int a = 1, b = 2, c;
c = func(a, b);
printf("%d\n", c);
}
{
float a = .1f, b = .2f, c;
c = func(a, b);
printf("%f\n", c);
}
{
double a = .1, b = .2, c;
c = func(a, b);
printf("%f\n", c);
}
return 0;
}
旧式的C语言方式是使用union和一个区分器:
union multi_num {
uint32_t small_num;
uint64_t large_num;
float float_num;
};
struct multi_type {
int discriminator;
union multi_num val;
};
int
add_fun (struct multi_type var1, struct multi_type var2, struct multi_type *ret_val)
{
if (var1.discriminator != var2.discriminator) {
return -1;
}
ret_val->discriminator = var1.discriminator;
switch (var1.discriminator) {
case 1:
ret_val->val.small_num = var1.val.small_num + var2.val.small_num;
break;
case 2:
ret_val->val.large_num = var1.val.large_num + var2.val.large_num;
break;
case 3:
ret_val->val.float_num = var1.val.float_num + var2.val.float_num;
break;
}
return 0;
}
struct multi_type var1, var2, var3 = {0};
var1.discriminator = 1;
var2.discriminator = 1;
var1.val.small_num = 1;
var2.val.small_num = 12;
ret = add_fun(var1, var2, &var3);
if (0 == ret) {
printf("add worked, ret is %d\n", var3.val.small_num);
} else {
printf("add failed\n");
}