返回一个指向函数的指针,该函数具有基于参数的不同签名

Return a pointer to function with varying signature based on argument

本文关键字:函数 于参数 参数 一个 返回 指针      更新时间:2023-10-16

我已经看到这个链接描述了一个固定签名示例,但想知道如何编写一个函数来返回指向函数的指针的函数,该函数的签名取决于调用函数的参数(如果可能的话)?

例:

假设我有

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