[英]How can I define a function pointer that takes the same arguments and return value as a given function?
For example, I have a function foo
: 例如,我有一个函数
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? 这可能吗?
You cannot do this at run-time (ie 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 (ie it could point to a float (*)(int,int)
or a char (*)(float)
). 想象一下,如果您可以执行此操作,并且以某种方式获得了类型可变的函数指针(即它可以指向
float (*)(int,int)
或char (*)(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 .
一种方法是使用Boost TypeTraits库 。
c ++是一种静态类型的语言,不允许您做自己想做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.