简体   繁体   English

如何定义一个函数指针,该函数指针具有与给定函数相同的参数并返回值?

[英]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.

相关问题 如何定义一个将任何类型的指针值作为参数的函数? - How can I define a function that takes as a parameter a pointer value of any kind? #define/macro 返回指向同一文件中给出的 function 的 function 指针 - #define/macro to return a function pointer to a function given in the same file 如何声明/定义一个 function 与给定的 function 指针具有相同的返回和参数类型? - How to declare/define a function with the same return and parameter types as a given function pointer? 函数如何将指针返回到带有函数的函数? - How function can return pointer to function that takes a function? 重载的运算符将函数指针作为参数,我该如何检索函数指针的参数 - An overloaded operator takes function pointer as parameter, how do i retrieve arguments of function pointer 如果找不到匹配的数据,如何定义一个函数以将指针返回“”值? - How to define a function to return a pointer to a “” value when no matching data is found? 我应该如何定义一个返回对指针的引用的函数? (引用指针与指向指针的指针) - How should I define a function that return reference to a pointer? (reference to pointer vs pointer to pointer) 如何定义一个模板化的 function ,它需要一个 map 和一个 lambda 来按值搜索映射对? - How can I define a templated function which takes a map and a lambda to search map-pair by value? 如何将成员函数指针传递给带有常规函数指针的函数? - How can I pass a member function pointer into a function that takes a regular function pointer? C++ isPrime function: How can I return a Boolean value from a function that takes an integer parameter? - C++ isPrime function: How can I return a Boolean value from a function that takes an integer parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM