当一个参数是常量时,在 C 中更改函数指针的签名 [英] Change signature of function pointer in C when one argument is constant

查看:56
本文介绍了当一个参数是常量时,在 C 中更改函数指针的签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 C 中使用快速排序,它的函数签名为 void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)),但我的比较函数的签名是 int (*compar)(const void *, const void*, const int),其中第三个参数在一次快速排序调用期间保持不变.

I want to use quicksort in C, which has a function signature of void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)), but the signature of my comparison function is int (*compar)(const void *, const void*, const int) with the third argument being constant during one call to quicksort.

举个例子,假设我想根据不同的范数(例如 L0、L1、L2 和 Linifinity 范数)对一组向量进行排序.它实际上是哪个范数,作为第三个参数传递给比较函数,但在调用 qsort 期间保持不变.是否可以以

As an illustration, assume that I want to sort an array of vectors according to different norms (L0, L1, L2 and Linifinity norm for example). Which norm it actually is, is passed as a third argument to the comparison function, but remains constant during the call of qsort. Is it possible to do an assignment in a form like

//Function declaration for parametric comparison
int cmp3(int* a_vec, int* b_vec, int x);

// Somewhere in main
int (*cmp2)(int, int);
cmp2 = cmp3(int*, int*, 2);//2 could mean L2 norm

能够调用类似的东西

qsort(a, 100, sizeof(a), cmp2);

我知道这行不通,但我希望它能让我知道我想要完成什么.此外,由于不同的比较方式的数量太多,因此无法制作不同的比较函数和调用 qsort.

I know this does not work, but I hope it gives an idea what I want to accomplish. Also it is not possible to make different comparison functions and calls to qsort as the number of different ways of comparing is too big.

推荐答案

这叫做部分函数应用,而您只能使用 C 中的包装器来实现类似的功能:

This is called partial function application, and you can only achieve something like this with wrappers in C:

int cmp3(int *a, int *b) {
    return cmp2(a, b, 2);
} 

如果您喜欢部分函数应用程序,或者可能是映射或纯函数,您可能需要研究函数式编程语言,例如 Haskell.

If you're into partial function application or maybe mappings or pure functions, you may want to look into functional programming languages, like Haskell.

这篇关于当一个参数是常量时,在 C 中更改函数指针的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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