用C函数式编程与宏"高阶函数"发电机 [英] Functional programming in C with macro "Higher Order Function" generators

查看:131
本文介绍了用C函数式编程与宏"高阶函数"发电机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注重认真,因为这是一个问题的地狱; - )

Pay attention carefully because this is a hell of a question ;-)

我想在C到使用泛型集合动作模板函数(如搜索,的foreach等),同时保持编译器的静态类型检查。这是相当简单的,当你在这个例子中使用简单的回调,如:

I want to use template functions for generic collection actions (like search, foreach, etc.) in C while maintaining compiler static type checking. It is fairly straightforward while you're using simple callbacks like in this example:

#define MAKE_FOREACH(TYPE)\
void foreach_##TYPE (TYPE[n] array, int n, void(*f)(TYPE)) {\
  for(int i = 0; i < n; i++) {\
    f(array[i]);\
  }\
}

所以你可以做这样的事情:

so you can do things like:

MAKE_FOREACH(int)
MAKE_FOREACH(float)

void intcallback(int x){
  printf("got %d\n", x);
}

void floatcallback(float x){
  printf("got %f\n", x);
}

int main(){
  int[5] iarray = {1,2,3,4,5};
  float[5] farray = {1.0,2.0,3.0,4.0,5.0};
  foreach_int(iarray, 5, intcallback);
  foreach_float(farray, 5, floatcallback);
}

如果我想实现与返回类型的回调,比如做一个映射功能,我可以这样做:

If I'd like to implement callbacks with return types, for example to make a "map" function, I could do:

#define MAKE_MAP(TYPE, RTYPE)\
RTYPE* map_##TYPE (TYPE[n] array, int n, RTYPE(*f)(TYPE)) {\
  RTYPE* result = (RTYPE*)malloc(sizeof(RTYPE)*n);\
  for(int i = 0; i < n; i++) {\
    result[i]=f(array[i]);\
  }\
}

到目前为止,一切都很好。问题来了,当我想我的回调函数接受任何数量的类型参数。

So far, so good. The problem comes now, when I want my callback functions to accept any number of typed arguments.

我们的想法是这样的:

#define MAKE_MAP(TYPE, RTYPE, ...)\
RTYPE* map_##TYPE (TYPE[n] array, int n, RTYPE(*f)(TYPE, __VA_ARGS__), __VA_ARGS__)
/*this would work for the declaration (because just the types would be enough)
but the  parameter names are missing :-s*/ \
{\
  RTYPE* result = (RTYPE*)malloc(sizeof(RTYPE)*n);\
  for(int i = 0; i < n; i++) {\
    result[i]=f(array[i], /*here the names of the parameters, in order*/);\
  }\
}

所以,你可以看到,我的声明的映射函数为:

MAKE_MAP(int, float, char)

捐赠:

float* map_int(int[n] array, int n, float(*f)(int, char), char);

但我想不出如何的实施的参数传递的preprocessor。这里就是我找你帮忙,想法和建议。

but I cannot figure how to implement the parameter passing with the preprocessor. Here is where I ask for your help, ideas and suggestions.

(顺便说一句,不要告诉我使用可变参数函数为模板,传递的va_list参数回调,因为所有这些东西是因为类型检查:-P的)

(By the way, don't tell me to use a variadic function as template and passing a va_list argument to the callback, because all this stuff was because of the type checking :-p)

推荐答案

如果你是在Linux / BSD Unix等,看一看的队列(3),入住 /usr/include/sys/queue.h - 它之前已经完成:)

If you are on Linux/BSD Unix, take a look at queue(3) and check into /usr/include/sys/queue.h - it's been done before :)

这篇关于用C函数式编程与宏&QUOT;高阶函数&QUOT;发电机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆