返回一个指向函数的指针,该函数具有基于参数的不同签名
Return a pointer to function with varying signature based on argument
我已经看到这个链接描述了一个固定签名示例,但想知道如何编写一个函数来返回指向函数的指针的函数,该函数的签名取决于调用函数的参数(如果可能的话)?
例:
假设我有
typedef void (*func1) (int);
typedef void (*func2) (int, int);
我想要一个函数get_func
,它根据整数参数的值返回指向一个或另一个的指针,例如: get_func1(0)
返回func1
; get_func2(1)
返回func2
.
我认为你不能那样做。
您可能想要做的是返回一个指向函数的指针,该函数将一些指针struct
因为它只是参数,并且在该struct
中您有可变数量的参数。
typedef void (*func1) (struct MyStruct*);
然后在MyStruct
里面:
struct MyStruct {
int param;
struct MyStruct* next;
};
或类似的东西。您可以将结构链接在一起,并将所有结构都读取为"参数"。
我知道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( "f1n" );
}
void f2(int, int) {
printf( "f2n" );
}
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);
}
http://rextester.com/ZLIXM68236
相关文章:
- 使用指向成员的指针将成员函数作为参数传递
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 如何制作一个将函数作为参数的类方法
- Arduino C++在构造函数中用参数声明对象数组
- C++线程中,没有重载函数接受 X 参数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将可变参数函数的参数封装在类实例中
- 如何使用模板化标准::函数作为参数?
- 如何在 c++ 中将函数作为参数传递?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 构造函数/函数声明参数列表中的统一初始化
- 将函数作为参数C++传递给类
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何定义依赖于参数包转换的函数的返回类型
- 以错误的顺序将函数应用于参数包中的每个元素
- C++等价于在python中传递lambda函数作为参数
- 将函数应用于参数包的每个元素的语言功能
- 依赖于参数的查找和函数模板
- 对依赖于参数的查找和友元函数定义的混淆