在 C 中将 func(const void *) 赋值给 func(void *)
我有一个函数,它接受函数指针并将其应用于列表。它的原型如下:
void applyList(List *, void applyFunc(void *));
现在我想提供一个打印列表中元素的函数。由于我没有修改列表元素,因此打印函数如下所示:
void printNode(const void *nodeData){
Data *dPtr=(Data*)nodeData;
printf("%s", dPtr->str );
}
//Usage
applyList(list, printNode);
但是,我收到编译器错误,指出
expected ‘void (*)(void *)’ but argument is of type ‘void (*)(const void *)’
我不想将 const
添加到 apply
's原型,因为我可能会提供一些修改数据的函数。对于如何处理这种情况有什么建议吗?
I have a function that takes a function pointer and apply it over a list. It's prototype is as follows:
void applyList(List *, void applyFunc(void *));
Now I want to supply a function that prints the element in the list. Since I'm not modifying the list element, the print function looks like this:
void printNode(const void *nodeData){
Data *dPtr=(Data*)nodeData;
printf("%s", dPtr->str );
}
//Usage
applyList(list, printNode);
However I got an compiler error saying
expected ‘void (*)(void *)’ but argument is of type ‘void (*)(const void *)’
I don't want to add const
to apply
's prototype, because I might supply some function that modifies the data. Any suggestion on how to deal with this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,在 C 中函数指针不是多态的。完全没有。尝试强制转换会导致未定义的行为。
唯一符合标准的出路是编写一个包装函数:
但是请注意,您的 const 在这里有点无用:
您刚刚抛弃了 const 声明。尝试将其保留在那里:
Unfortunately, in C function pointers are not polymorphic. At all. Attempting to force a cast leads to undefined behavior.
Your only standard-conforming way out is to write a wrapper function:
Note, however, that your const is kind of useless here:
You just casted away the const declaration. Try to keep it on there:
那么就没有明智的解决方案。您无法修改该数据,这就是它被标记为
const
的原因。Then there is no sane solution. The data isn't yours to modify, which is why it's marked
const
.