c - c中的泛型求和函数

标签 c

是否可以用 C 编写通用求和函数?

我正在尝试编写一个处理任何数字类型的求和函数。

double sum(void* myArrayVoidPtr, size_t arrayLength, int arrayType){
    int i;
    double result = 0;

    //The goal is to make this next line depend on arrayType
    //e.g. if(arrayType == UINT16)
    unsigned short* myArrayTypePtr = (unsigned short*) myArrayVoidPtr;

    for(i = 0; i < arrayLength; i++){
        result += *myArrayTypePtr;
        myArrayTypePtr++;
    }
    return result;
}

最佳答案

在 C 中创建泛型函数是不可能的。与 C++ 不同,您没有 templates .模板允许您创建同一函数的多个版本,不同的是 type(即 - intfloat 或任何 class ) 他们“接受”。 这意味着函数被编译了不止一次

C 没有模板,但您可以为此编写一个宏。这基本上等同于 C++ 的模板,只是功能没那么强大。不过它将是“内联的”,而不是真正的函数。

#define SUM(arr, len, sum) do { int i; for(i = 0; i < len; ++i) sum += arr[i]; } while(0);

int main(void) {
    int i_arr[] = {1,2,3};
    double d_arr[] = {1.5, 2.5, 3.5};
    int sum = 0;
    double d_sum = 0;
    SUM(i_arr, 3, sum)
    SUM(d_arr, 3, d_sum);
    printf("%d, %f\n", sum, d_sum);
    return 0;

}

输出:

6, 7.500000

关于c - c中的泛型求和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670860/

相关文章:

c - 长数据类型如何存储在内存中?

c++ - nrf51882a 入门

c - 错误 C2065 : 'i' : undeclared identifier in VS2012, 但不是 Mac

c - mpn_copyi 在 GMP C 库中到底做了什么?

c - 如何在树莓派上运行没有操作系统的 C 程序?

cuBLAS 同步最佳实践

搜索数组以查找字符序列的 C 程序

python - 为什么以下代码在 codechef 中给出段错误,但在其他地方却工作得绝对正确

c - 无法理解二叉搜索树中插入的逻辑

c++ - mmap 文件,其中包含一个不受该文件支持的额外页面