我想用C语言编写一些函数,但它们必须对所有数值类型(int、float、double)都可用。什么是好的实践?在void上使用指针(当然还有指向函数的指针)?或者为每种类型编写不同的函数?
例如:
float func(float a, float b) {
return a+b;
}
发布于 2016-01-11 23:42:49
如果您可以使用C11,_Generic可以提供以下帮助:
#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;
}
发布于 2016-01-11 23:37:19
由于C没有像C++ (编辑:除非您使用具有_Generic的C11 )那样的多分派(函数重载),所以您必须为每种类型的函数命名不同,如funcInt(int a, int b); funcFloat(float a, float b);
或
使用允许typeof()
to kind of fake it的GCC风格的语句表达式宏。
https://stackoverflow.com/questions/34733044
复制