-4

I am working with function pointer in c++ , and i am wonderring if any function pointer type which can use for every function, dont care about return value, list argument or how many argument. If it is possible, how is it work?

example:

I have some functions:

void F1(void);

void F2(int);

int F3(int, char*);

float F4(int, float);

int F5(MyClass);

....

if: i have

typedef (void) (*fp1)(void); i can call : fp1 x = &F1;

if: i have

typdef (float) (*fp2)(int, float); i can call : fp2 x = &F4;

now I need some kind of function pointer to store all of them.

something like this:

typedef void(function_pointer)(void)

or typedef void(function_pointer)(void, ...) // but both dont work.

And one more infomation: i have tried to use template, but it didn't solve my problem Thanks.

Stevie
  • 3
  • 1
  • 2
  • oh. i'm sorry. I forget mention that. I'm focussing in c++. – Stevie Aug 25 '15 at 15:35
  • You should give an example code of how you imagine using said pointer. Do you mean just casting to `void*`, or having a function of the type `void func(void *param)`? – sashoalm Aug 25 '15 at 15:37
  • possible duplicate of [Find out Type of C++ Void Pointer](http://stackoverflow.com/questions/1718412/find-out-type-of-c-void-pointer) –  Aug 25 '15 at 15:39
  • The target type of a function pointer helps reduce errors in your program. For example, preventing the incorrect function being called or verifying the calling code has the correct number of parameters for the target function. Is there a reason you want to bypass this safety check (during compilation)? – Thomas Matthews Aug 25 '15 at 15:52
  • Thanks Jarrod, but it is not what I looking for. Thanks Thomass, you have good idea, the implicit behaviour may be let me control my my code worse. – Stevie Aug 25 '15 at 16:04

1 Answers1

2

The standard promises that you can use reinterpret_cast to convert one function pointer type to another, and this conversion is reversible. However, it also requires that you cast the function pointer back to its original type before using it.

[expr.reinterpret.cast]

A pointer to a function can be explicitly converted to a pointer to a function of a different type. The effect of calling a function through a pointer to a function type that is not the same as the type used in the definition of the function is undefined. Except that converting an rvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

Therefore, you need to keep track somewhere else what kind of function you put in the variable, so you can cast it back to the correct type before you use it. As a result, the ability to cast function types to each other is of only marginal value; you could have used a union to achieve the same effect.

Community
  • 1
  • 1
Raymond Chen
  • 44,448
  • 11
  • 96
  • 135