0

I've seen this link describing a fixed signature example but would like to know how to write a function that returns a pointer to a function whose signature depends on the argument to the calling function (if it is even possible)?

Example:

Suppose I have

typedef void (*func1) (int);
typedef void (*func2) (int, int);

I would like to have a function get_func that returns a pointer to one or the other based on, say, the value of an integer argument, e.g.,: get_func1(0) returns func1; get_func2(1) returns func2.

Community
  • 1
  • 1
squashed.bugaboo
  • 1,338
  • 2
  • 20
  • 36

3 Answers3

3

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".

yamafontes
  • 5,552
  • 1
  • 18
  • 18
  • @Haole: I suspected the same and you might be right. I'll have to think about it some more. But might end up doing something like you suggest. – squashed.bugaboo Nov 12 '13 at 22:50
2

I know Iĺl get a lot of downvotes here, but if you want something, are eager to get it, know the risk and consent with it, you can lower the compiler checks to get what you want.

Below I show you one way to get want you want. I dont recomend to do that, but if you believe that it is exactly what you want, go on.

#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));
}

As said before, reinterpret_cast is lowering the compiler checks, basicly saying that you are responsible for everything wrong that could happens

Amadeus
  • 10,199
  • 3
  • 25
  • 31
0

how about

#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);
}

http://rextester.com/ZLIXM68236

Shelwien
  • 2,160
  • 15
  • 17