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

sor*_*orh 3 c types

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

typedef enum
{

} type1_t;

typedef enum
{

} type2_t;

void myfunc(typex_t foo)
{

}
Run Code Online (Sandbox Code Playgroud)

Bob*_*b__ 6

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

一个普通的选择

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

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

#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"
}
Run Code Online (Sandbox Code Playgroud)

在这里测试。