简体   繁体   English

了解高阶函数如何在 C 中工作

[英]Understanding how higher order functions work in C

So usually I would declare any function pointer like this:所以通常我会像这样声明任何函数指针:

typedef size_t (*hash_function)(const int *);

and then later use it in another function然后在另一个函数中使用它

HashTable *hash_table_create(const hash_function hash)

so for any function which fulfills the hash_function definition like所以对于任何满足 hash_function 定义的函数,如

size_t hash_modulo(const int *parameters)
size_t hash_universal(const int *parameters)
...

I can use them as a parameter我可以将它们用作参数

hash_table_create(hash_modulo)

The problem is : My IDE (Clion) complains that the parameters in this case do not match (the code works tho).问题是:我的 IDE (Clion) 抱怨这种情况下的参数不匹配(代码有效)。 Specifically it doesn't seem to accept passing hash_function as a parameter type, but will accept if I use size_t (*hash_function)(const int *) instead.具体来说,它似乎不接受将hash_function作为参数类型传递,但如果我使用size_t (*hash_function)(const int *)代替,它会接受。 What am I missing here?我在这里缺少什么?

Is my code right and my IDE wrong or vice versa?我的代码是对的而我的 IDE 是错的,反之亦然?

Thanks in advance!提前致谢!

Edit 1: The exact error message is: Types 'hash_function' and size_t(const int *)' are not compatible编辑 1:确切的错误消息是: Types 'hash_function' and size_t(const int *)' are not compatible

Edit 2: This seems to be a Clion Bug编辑 2:这似乎是一个 Clion错误

CLion seems to have a bug (possibly). CLion 似乎有一个错误(可能)。 The function names are of the type size_t(const int *) .函数名称的类型为size_t(const int *) Now, since functions are implicitly convertible to function pointers, your code is perfectly valid C.现在,由于函数可以隐式转换为函数指针,因此您的代码是完全有效的 C。

The CLion syntax checker probably doesn't take implicit conversions into account. CLion 语法检查器可能不会考虑隐式转换。 If you obtain a function pointer explicitly from the function name the error should go away:如果您从函数名称中显式获取函数指针,则错误应该消失:

hash_table_create(&hash_modulo); // Note the ampersand

I think the problem is that you typedef the function as const我认为问题在于您将函数typedefconst

HashTable *hash_table_create(const hash_function hash)

and the other functions you want to put in as parameters aren't declared const并且您想作为parameters放入的其他函数未声明为const

size_t hash_modulo(const int *parameters)
size_t hash_universal(const int *parameters)

Edit:编辑:

This works fine in CodeBlocks这在 CodeBlocks 中工作正常

Change this:改变这个:

size_t hash_modulo(const int *parameters)
size_t hash_universal(const int *parameters)

into this:进入这个:

hash_function hash_modulo;
hash_function hash_universal;

and then this work fine:然后这个工作正常:

hash_table_create(hash_modulo);
hash_table_create(hash_universal);

Explanation in the comment below.在下面的评论中解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM