ç多种功能 [英] C multiple types function

查看:120
本文介绍了ç多种功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C来写一些功能,但它们必须适用于所有数字类型(整型,浮点,双)。什么是好的做法呢?使用上的空指针(和指针当然功能)?或者写一个不同的功能每一个类型?

例如:

 浮动FUNC(浮动,浮动B){
   返回A + B;
 }


解决方案

如果你可以使用C11,的 _Generic 可以帮助:

 的#include<&stdio.h中GT;INT ifunc(int类型的,INT B){返回A + B; }
浮ffunc(浮动,浮动B){返回A + B; }
双dfunc(双一,双二){返回A + B; }#定义FUNC(X,Y)\\
   _Generic((X),INT:ifunc,浮动:ffunc,双:dfunc,默认:ifunc)(X,Y)INT主要(无效)
{
    {
        诠释一个= 1,B = 2,C;
        C = FUNC(A,B);
        的printf(%d个\\ N,C);
    }
    {
        浮动= .1F,B = .2f,C;
        C = FUNC(A,B);
        的printf(%F \\ N,C);
    }
    {
        双A = 0.1,B = 2,℃;
        C = FUNC(A,B);
        的printf(%F \\ N,C);
    }
    返回0;
}

I'd like to write some functions in C but they have to be available for all numeric types (int, float, double). What is good practise? Use pointer on void (and pointer to function of course)? Or write a different function for every type?

For example:

 float func(float a, float b) {
   return a+b;
 }

解决方案

If you can use C11, _Generic can help:

#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;
}

这篇关于ç多种功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆