我想在编译时通过类型执行“static dispatching ”。
具体来说,有一个函数系列(按类型参数化),我想根据参数的类型从该系列中选择一个函数(在编译时)。
在 C11
中,可以使用 _Generic()
来完成此操作。
例如,以下代码有效。
// gcc generic.c -o generic && ./generic
#include <stdio.h>
void foo_int() { printf("%s\n", __func__); } // Arbitrary code to show that this works
void foo_float() { printf("%s\n", __func__); } // Arbitrary code to show that this works
void foo_double(){ printf("%s\n", __func__); } // Arbitrary code to show that this works
#define foo_api0(VAL) \
_Generic(VAL, \
int: foo_int, \
float: foo_float, \
double: foo_double \
)()
int main(){
foo_api0(2);
foo_api0(4.f);
foo_api0(8.);
}
但是,现在假设在宏 foo_api
中,
我不想传递所需类型的值,
但我想传递所需的类型本身。
(原因为什么对于当前的讨论并不重要。假设这些原因存在。)
例如,代替
foo_api0(2);
foo_api0(4.f);
foo_api0(8.);
我想做
foo_api1(int);
foo_api1(float);
foo_api1(double);
可以通过使用类型本身创建辅助变量(即类型的“见证者”)来实现这一点:
#define foo_api1(TYPE) ({ \
TYPE witness; \
_Generic(witness, \
int: foo_int, \
float: foo_float, \
double: foo_double \
)(); \
})
然后两个 API 都可以工作:
int main(){
foo_api0(2);
foo_api0(4.f);
foo_api0(8.);
foo_api1(int);
foo_api1(float);
foo_api1(double);
}
我的问题是:
有没有办法不使用这样的辅助变量来做到这一点? (也许 C 中有一个宏/关键字可以根据类型本身而不是该类型的变量来执行操作?)
例如,如果有这样的东西就太好了:
#define foo_api1(TYPE) ({ \
_Generic(TYPE, \
int: foo_int, \
float: foo_float, \
double: foo_double \
)(); \
})
最佳答案
to pass the desired type itself.
形成一个复合文字:(TYPE){0}
#define foo_api1(TYPE) \
_Generic((TYPE){0}, \
int: foo_int, \
float: foo_float, \
double: foo_double \
)()
int main(){
foo_api1(int);
foo_api1(float);
foo_api1(double);
}
发送至地址@Eric Postpischil评论:
形成复合文字作为指针:(TYPE *){0}
#define foo_api2(TYPE) \
_Generic((TYPE *){0}, \
int *: foo_int, \
float *: foo_float, \
double *: foo_double \
)()
关于C11 : Using `_Generic()` (or something) for types themselves (not instances of types)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61199132/