参数不确定的函数指针 [英] Function pointer with undetermined parameter
问题描述
我想要一个可以使用各种类型参数的函数指针.我该怎么办?
I want to have a function pointer that can take various types of parameters. How do I do that?
下面的示例(第1行)中,我希望void (*fp)(int)
也能够采用void (*fp)(char*)
.以下代码无法正确编译,因为我在期望将int传递给char *的地方,因此编译以下代码会给您警告(并且无法正常工作).
The following example (line 1), I want void (*fp)(int)
to be able to take void (*fp)(char*)
as well. The following code does not properly compile because I'm passing char* where int is expected so compiling the following code will give you warnings (and won't work properly).
void callIt(void (*fp)(int))
{
(*fp)(5);
}
void intPrint(int x)
{
printf("%d\n", x);
}
void stringPrint(char *s)
{
printf("%s\n", s);
}
int main()
{
void (*fp1)(int) = intPrint;
callIt(fp1);
void (*fp2)(char*) = stringPrint;
callIt(fp2);
return 0;
}
注意:我知道尝试将整数5作为char *参数传递是愚蠢的,但这不是此问题的关注点.如果需要,可以将char *替换为float.
Note: I know that attempting to pass integer 5 as char* parameter is stupid, but that's not the concern for this question. If you want, you can replace char* with float.
推荐答案
我会说使用void (*fp)(void*)
,然后将指针传递给变量并将其强制转换为void *.这很hacky,但是应该可以.
I would say use void (*fp)(void*)
, then pass in pointers to your variables and cast them as void*. It's pretty hacky, but it should work.
例如:
void callIt(void (*fp)(void*))
{
int x = 5;
(*fp)((void*)&x);
}
这篇关于参数不确定的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!