我已经看到此链接描述了一个固定签名示例,但想知道如何编写一个函数,该函数返回一个指向函数的指针,该函数的签名取决于调用函数的参数(如果可能的话)?
例子:
假设我有
typedef void (*func1) (int);
typedef void (*func2) (int, int);
我想要一个函数,它根据整数参数的值返回get_func指向其中一个或另一个的指针,例如
:
返回。get_func1(0)func1get_func2(1)func2
我已经看到此链接描述了一个固定签名示例,但想知道如何编写一个函数,该函数返回一个指向函数的指针,该函数的签名取决于调用函数的参数(如果可能的话)?
例子:
假设我有
typedef void (*func1) (int);
typedef void (*func2) (int, int);
我想要一个函数,它根据整数参数的值返回get_func指向其中一个或另一个的指针,例如
:
返回。get_func1(0)func1get_func2(1)func2
I don't think you can do it like that.
What you may want to do instead is return a pointer to a function that takes some struct pointer as it's only argument, and inside that struct you have a variable number of parameters.
typedef void (*func1) (struct MyStruct*);
and then inside MyStruct:
struct MyStruct {
int param;
struct MyStruct* next;
};
Or something like that. You can link the structs together, and read all of them as "params".
我知道 Iĺl 在这里得到了很多反对意见,但是如果你想要一些东西,渴望得到它,知道风险并同意它,你可以降低编译器检查以获得你想要的东西。
下面我将向您展示一种获得想要的方法。我不建议这样做,但是如果您相信这正是您想要的,请继续。
#include <iostream>
using namespace std;
typedef void (*func1) (int);
typedef void (*func2) (int, int);
void f1(int)
{
cout << "f1" << endl;
}
void f2(int, int)
{
cout << "f2" << endl;
}
void call(int x, void *t)
{
if ( x )
reinterpret_cast<func1>(t)(0);
else
reinterpret_cast<func2>(t)(0, 0);
}
int main()
{
call(0, reinterpret_cast<void*>(f1));
call(1, reinterpret_cast<void*>(f2));
}
如前所述,reinterpret_cast降低编译器检查,基本上是说您对可能发生的所有错误负责
怎么样
#include <stdio.h>
typedef void (*func1) (int);
typedef void (*func2) (int, int);
union func12 {
void* f0;
func1 f1;
func2 f2;
};
void f1(int) {
printf( "f1\n" );
}
void f2(int, int) {
printf( "f2\n" );
}
func12 get_func( int x ) {
func12 r;
if( x ) r.f2=f2; else r.f1=f1;
return r;
}
int main() {
get_func(0).f1(0);
get_func(1).f2(0,0);
}