Phi*_*rad 5 c delegates function-pointers anonymous-function unions
我希望能够将一个函数一般地传递给C 中的一个函数。我已经使用 C 几年了,我知道实现正确的闭包和高阶函数的障碍。这几乎是不可逾越的。
我搜索了 StackOverflow 以查看其他消息来源对此事的看法:
...除了使用可变参数或程序集之外,没有人有一个银弹一般的答案。我没有汇编的骨头,但如果我能在宿主语言中有效地实现一个特性,我通常会尝试。
我喜欢高阶函数,但我会在紧要关头满足于委托。我怀疑通过类似下面的代码,我可以在 C 中获得一个可行的委托实现。
想到了这样的实现:
enum FUN_TYPES {
GENERIC,
VOID_FUN,
INT_FUN,
UINT32_FUN,
FLOAT_FUN,
};
typedef struct delegate {
uint32 fun_type;
union function {
int (*int_fun)(int);
uint32 (*uint_fun)(uint);
float (*float_fun)(float);
/* ... etc. until all basic types/structs in the
program are accounted for. */
} function;
} delegate;
Run Code Online (Sandbox Code Playgroud)
用法示例:
void mapint(struct fun f, int arr[20]) {
int i = 0;
if(f.fun_type == INT_FUN) {
for(; i < 20; i++) {
arr[i] = f.function.int_fun(arr[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这种处理委托的方法有一些明显的缺点:
注:越便携、越高效越好
另外,注意:我听说过Don Clugston对 C++ 的快速委托。但是,我对 C++ 解决方案不感兴趣——只是 C 。
| 归档时间: |
|
| 查看次数: |
1709 次 |
| 最近记录: |