C全部类型参数 [英] C all type parameter

查看:84
本文介绍了C全部类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

我个人会这样做:



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

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

这会让你用很多开关编写难看的代码,但如果仔细彻底地完成

类似于:

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

//函数
int解析(void * arg,enum_type arg_type)
{
if(arg == NULL)返回-1;

switch(arg_type)
{
case BYTE_VALUE:
byte value =(byte)* arg;
//在这里工作
case INT_VALUE:
// etc
}

return something;
}

编辑:假设您不需要可变参数函数对我来说似乎是你想要的)


How can I write a function which accepts a parameter of a generic type in C? (such as an int, a char...)

解决方案

I'd personally do it like this:

1) send a pointer to void * as the first parameter

2) send a second parameter which tells you what the void * is (an enum for the possibilities) and cast parameter 1 to that

This would make you write ugly code with lots of switches, but might work if done carefully and thoroughly tested.

Something like:

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

Edit: that is assuming you don't want variadic functions (which did not seem to me were what you wanted)

这篇关于C全部类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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