Is store function pointers with different parameters in a vector of void pointers.
unordered_map<string, vector<void*> > List;
template <typename T>
void Listen(string Name, function<void(T)> Function)
{
List[Name].push_back(&Function);
}
Then I want to call them, assuming that T is the same type for Fire as used for the Listen.
template <typename T>
void Fire(string Name, T Data)
{
auto Functions = List[Name];
for (auto i = Functions.begin(); i != Functions.end(); ++i)
{
(function<void(T)>)i)(Data);
}
}
But I get a compiler error which reads error C2064: term does not evaluate to a function taking 1 arguments in file ...\vc\include\xrefwrap 431 1.
What am I doing wrong?
For one, you’re taking the address of a parameter, here:
Then you’re trying to convert an iterator object to a
std::functionobject here:What you trying to do can be done, like this, although it’s not pretty, to put it mildly:
It can break in lot of ways, for example you have no control that the function, registered under some name in
Listenis called with the correct argument inFire– consider callingListen<int> ("foo", f);and then doingFire<double> ("foo", 3.14);Another approach – just pass closures for callbacks: