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!

3
  • 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"? Commented Nov 11, 2016 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. Commented Nov 11, 2016 at 23:49
  • probably you should see the answer of a similar question asked here stackoverflow.com/questions/11037393/… Commented Nov 11, 2016 at 23:52

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

4 Comments

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!
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))>);
next, you can declare function pointer types like this: SomeReturnType (* function_1)(Class_1 c1) f1; SomeReturnType (* function_2)(Class_2 c2) f2;
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; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.