How do I create an array of function pointers of different prototypes?

  • A+

I have a few functions defined like this:

ParentClass*    fun1(); ParentClass*    fun2(); ParentClass*    fun3(bool inp=false); ChildClass*     fun4(); ChildClass*     fun4(int a=1, int b=3); 

I would like to put them into an array of some kind as follows:

void* (*arr[5])() = {     (void* (*)())fun1,     (void* (*)())fun2,     (void* (*)())fun3,     (void* (*)())fun4,     (void* (*)())fun5 } 

Now I would like to use this array of functions simply as

for(int i=0; i<5; i++)     arr[i](); 

Now I realize here that the issue is void* (*arr[5])(), but given that I only want to use the functions without supplying an argument, I would like all of these to be part of the same array.

These are very C-style ways to do it, though. Is there a better way to do it using Templates in C++?


C-style or not, what you have is straight undefined behaviour. Use lambdas:

void (*arr[5])() = {     [] { fun1(); },     [] { fun2(); },     [] { fun3(); },     [] { fun4(); },     [] { fun5(); } }; 

These are okay because they perform the call through the function's correct type, and are themselves convertible to void (*)().


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: