伪泛型用C [英] Pseudo-generics in C
问题描述
我需要实现一些方法,做的东西不同种类数阵列。通常情况下,我会使用泛型那份工作,但由于C没有提供给他们,我现在尝试使用宏来模仿他们。
I need to implement some methods that do stuff with different kinds of number arrays. Usually, I'd use generics for that job, but as C doesn't provide them, I'm now trying to emulate them using macros.
这里是什么我试图做一个例子:
Here's an example of what I'm trying to do:
#ifndef TYPE
#define TYPE int
#endif
TYPE get_minimum_##TYPE (TYPE * nums, int len){
TYPE min = nums[0];
for (int i = 1; i < len; i++) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
不过,这将无法编译。铛错误消息:
However, this won't compile. The clang error message:
错误:预期';'经过顶级声明符
error: expected ';' after top level declarator
有没有办法在C这样做吗?或者我需要实现这个每种类型的手?
Is there any way to do this in C? Or do I need implement this for every type by hand?
推荐答案
您可以做这样的事情在头文件:
You can do something like this in a header file:
//
// generic.h
//
#define TOKENPASTE(x, y) x ## y
#define GET_MINIMUM(T) TOKENPASTE(get_minimum_, T)
TYPE GET_MINIMUM (TYPE) (TYPE * nums, int len){
TYPE min = nums[0];
for (int i = 1; i < len; i++) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
然后的#include
它为每个需要的类型,例如一个源文件:
and then #include
it in a source file for each required type, e.g.:
//
// generic.c
//
#define TYPE int
#include "generic.h"
#undef TYPE
#define TYPE float
#include "generic.h"
#undef TYPE
您可以通过在preprocessor运行它测试:
You can test this by running it through the preprocessor:
$ gcc -E generic.c
int get_minimum_int (int * nums, int len){
int min = nums[0];
for (int i = 1; i < len; i++) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
float get_minimum_float (float * nums, int len){
float min = nums[0];
for (int i = 1; i < len; i++) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
这篇关于伪泛型用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!