如何定义一个函数指针,它采用与给定函数相同的参数和返回值?

发布于 2024-11-01 08:29:31 字数 372 浏览 2 评论 0原文

例如,我有一个函数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

°如果伤别离去 2024-11-08 08:29:31

您不能在运行时(即动态地)执行此操作;请记住,所有类型(函数指针都是类型)都是在编译时静态确定的。

想象一下,如果您可以这样做,并且您以某种方式获得了一个类型为变量的函数指针(即它可以指向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 a 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.

柏林苍穹下 2024-11-08 08:29:31

C++ 是一种静态类型语言,不允许做你想做的事情。

c++ is a static typed language, and doesn't allow to do what you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文