Is there a way to store void functions with different parameters in a vector? The number of parameters is always one, only the type differs. The parameter type can be a default type like int, a pointer to my own object like example* or any other type.
What I do for now is using a vector of functions with a void pointer as parameter. So I can pass everything. But I want to get rid of the back casting in all the functions.
unordered_map<string, function<void(void*)> > List;
void Callback(string Name, function<void(void*)> Function)
{
List[Name].push_back(&Function);
}
Callback("event", [](void* x){
int value = *(int*)x;
cout << value << endl;
});
Here is an example to illustrate what I would like to have. Please note the template syntax I would prefer. Therefore I would need to store all the functions in a container.
vector<function<void(...)> > List; // need something other than a std vector
template <typename T>
void Callback(string Name, function<void(T)> Function)
{
List[Name].push_back(&Function);
}
Callback<int>([](int x){
cout << x << endl;
});
This application is performance related since it is an essential part of a realtime rendering engine.
Edit: I solved the point of storing functions without parameters, so this is not part of the question anymore what makes the question more clear and straightforward.
vector<Foo> vwhereFoois just the right type. You want to callv[3](x). What type do you wantxto be?WindowResizeprovides aVector2ifor the new height and width. All registered callbacks must have none or just aVector2iparameter. But as I said my actual implementation uses void pointers so only the programmer knows the type.WindowResizehas data of typeVector2ietc, and he wants to express this knowledge using only statically type safe constructs of the language. Why he lumps all callbacks of all possible types in the same vector then? By doing this, he throws away the knowledge. Why not separate callbacks that accept anintfrom those that acceptVector2ietc in a different variables, of different types? Then each event type will know where to find relevant callbacks.