C 所有类型参数

标签 c function

如何在 C 中编写接受泛型参数的函数? (比如一个int,一个char...)

最佳答案

我个人会这样做:

1) 发送一个指向void *的指针作为第一个参数

2) 发送第二个参数告诉你 void * 是什么(可能性的枚举)并将参数 1 转换为它

这会让您编写带有大量开关的丑陋代码,但如果仔细完成并经过全面测试,可能会奏效。

类似于:

// the enum:
BYTE_VALUE = 1; INT_VALUE = 2, CHAR_VALUE = 3 etc

// the function
int parse(void *arg, enum_type arg_type)
{
    if (arg == NULL) return -1;

    switch(arg_type)
    {
    case BYTE_VALUE:
        byte value = (byte) *arg;
        // do work here
    case INT_VALUE:
     // etc
    }

    return something;
}

编辑:假设您不想要可变参数函数(在我看来这不是您想要的)

关于C 所有类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662229/

相关文章:

javascript - 如何通过函数调用访问回调

python - 将函数传递给函数

python - 清除函数外的数据(列表/字典/元组)

c - 如何遍历多级链表?

c - 来自整数的 Strcmp 指针,无需强制转换

java - 编程新手 : What is the difference between run time error and compilation error?

function - 在模块中包含的函数中添加类型

Python 诅咒 : module function vs instance function

c++ - 对指针的误解

c - 当我返回一个多维数组时,如何将我的函数中的内容传回我的结构