C多种类型的功能

Jos*_*h89 3 c polymorphism types function

我想在C中编写一些函数,但它们必须适用于所有数字类型(int,float,double).什么是好习惯?在void上使用指针(当然还有指向函数的指针)?或者为每种类型写一个不同的功能?

例如:

 float func(float a, float b) {
   return a+b;
 }
Run Code Online (Sandbox Code Playgroud)

Dav*_*eri 5

如果你可以使用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;
}
Run Code Online (Sandbox Code Playgroud)