如何定义一个函数指针,它采用与给定函数相同的参数和返回值?
例如,我有一个函数 foo
:
int foo(int a, int b)
{
return a + b;
}
我可以定义一个函数指针:
int (*pfoo)(int, int);
但是如何在程序中动态地执行此操作?
我想要一个函数,它接受一个函数作为参数,并返回一个函数指针,该指针接受与给定函数相同的参数和返回值。
然后我可以像这样使用它:
void* pfoo = getFuncPtrFromFunc(foo);
它执行上面代码的操作。
这可能吗?
For example, I have a function foo
:
int foo(int a, int b)
{
return a + b;
}
I can define a function pointer:
int (*pfoo)(int, int);
But how can I do this dynamically in program?
I want a function that takes a function as a parameter, and return a function pointer that takes the same arguments and return value as a given function.
Then I can use it like this:
void* pfoo = getFuncPtrFromFunc(foo);
Which does what the code above did.
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在运行时(即动态地)执行此操作;请记住,所有类型(函数指针都是类型)都是在编译时静态确定的。
想象一下,如果您可以这样做,并且您以某种方式获得了一个类型为变量的函数指针(即它可以指向
float (*)(int,int)
或一个char (*)(float)
)。您如何能够调用它并提供有意义的参数列表?但是,您可以在编译时获取此信息;一种方法是使用 Boost TypeTraits 库。
You cannot do this at run-time (i.e. dynamically); remember that all types (and function pointers are types) are statically determined at compile-time.
Imagine if you could do this, and you somehow obtained a function-pointer whose type was variable (i.e. it could point to a
float (*)(int,int)
or achar (*)(float)
). How would you ever be able to call that and provide a meaningful list of arguments?You can, however, get this information at compile-time; one way is to use the Boost TypeTraits library.
C++ 是一种静态类型语言,不允许做你想做的事情。
c++ is a static typed language, and doesn't allow to do what you want.