1

I am trying to make a vector of function pointers for a class Menu. But I don't know how to define it, since the pointers to the functions I want to add have different types of arguments and some don't have any at all.

What I envision is something like this:

vector<SomeReturnType(*)(SomeArgType)> functions;

Where I can add functions whose definitions are:

SomeReturnType function_1(Class_1 c1);
SomeReturnType function_2(Class_2 c2);
SomeReturnType function_3();

Adding just like this:

functions.push_back(function_1(object_of_Class_1));
functions.push_back(function_2(object_of_Class_2));
functions.push_back(function_3();

But that's obviously not possible. What is the best way to do this?

Thank you for your attention. Cheers!

Daniel Marques
  • 506
  • 5
  • 20
  • You cannot put them in a vector. Vectors store things that are all of the same type. If you could put different types in a vector, how would you use it? `functions[i].(??? what's inside ???)` There's no way to do "this", perhaps tell us you want problem you are trying to solve with "this"? – n. m. could be an AI Nov 11 '16 at 23:46
  • 1
    Well, you could put them into a vector if you cast them all to void* first. They're just pointers, after all. But presumably you want to call these functions at some point, so you would need to know how to cast each void pointer back to the correct function signature to do that. Perhaps what you really want is a vtable, which you get by making a base class with virtual functions. – Dan Korn Nov 11 '16 at 23:49
  • probably you should see the answer of a similar question asked here http://stackoverflow.com/questions/11037393/c-function-pointer-to-functions-with-variable-number-of-arguments – hrishi Nov 11 '16 at 23:52

1 Answers1

1

You could create a vector of pairs. The first element of the pair could be set to an enum indicating the type of function and the second element would be the function pointer type-casted to a void*.

std::vector<pair<int, void *> > functions;
Vivek
  • 320
  • 1
  • 5
  • That sounds great but I am too much of a novice to understand how to do that myself. Could you please write a simple example? I would appreciate it very much! Thank you for the quick answer too! – Daniel Marques Nov 12 '16 at 00:11
  • 1
    you can fill in the vector like this:functions.push_back(pair<0, (void *)(function_1(object_of_Class_1))>); functions.push_back(pair<1, (void *)(function_2(object_of_Class_2))>); – Vivek Nov 13 '16 at 22:07
  • 1
    next, you can declare function pointer types like this: SomeReturnType (* function_1)(Class_1 c1) f1; SomeReturnType (* function_2)(Class_2 c2) f2; – Vivek Nov 13 '16 at 22:13
  • 1
    next, when you are reading the vector back, you can say: if (functions[0].first == 0) { f1 = functions[0].second; } else if (functions[0].first ==1) { f2=functions[0].second; } – Vivek Nov 13 '16 at 22:15