允许两种数据类型的 C 函数

时间:2021-01-14 14:04:35

标签: c types

也许这只是一个愚蠢的问题,但我想知道是否有一种方法可以在同一个函数参数中允许两种数据类型,这种多态性最终会做同样的事情,只是为了过滤掉一些垃圾输入。< /p>

typedef enum
{

} type1_t;

typedef enum
{

} type2_t;

void myfunc(typex_t foo)
{

}

2 个答案:

答案 0 :(得分:6)

您可以考虑采用不同的方法,涉及 C11 功能之一。

A generic selection

<块引用>

提供一种在编译时根据控制表达式的类型选择多个表达式之一的方法。

你最终会得到一些代码重复,但也会有一个通用的“接口”。

#include <stdio.h>

void myfunc_int(int x){
    printf("int: %d\n", x);
}
void myfunc_float(float y){
    printf("float: %f\n", y);
}

#define myfunc(X) _Generic((X),     \
    int : myfunc_int,               \
    float : myfunc_float            \
) (X)

int main(void)
{
    myfunc(3.14f);

    myfunc(42);

//    myfunc(1.0);
//           ^ "error: '_Generic' selector of type 'double'
//                    is not compatible with any association"
}

可测试 here

答案 1 :(得分:3)

标记联合

您可以使用联合:

typedef union
{
    type1_t t1;
    type2_t t2;
} UnionType;

您需要以某种方式知道 t1t2 是否处于活动状态。为此,您可以传递一个额外的枚举值(您希望允许的每种类型的不同值):

enum types
{
    TYPE1,
    TYPE2
};

将它组合到一个结构体中,您就得到了 typex_t

typedef struct
{
    enum types type; // this is also called a type tag
    UnionType content;
} typex_t;

或更紧凑(非标准)

typedef struct
{
    enum { TYPE1, TYPE2 } type;
    union { type1_t t1; type2_t t2; } content;
} typex_t;

整个 struct union 构造也称为标记联合。

相关问题