I am trying to use std::map to map numerical IDs to function handlers: All function handlers take two integers and return an integer. Handler 100 would calculate the product.
When preparing the map, the compiler throws prog.cc:16:17: error: no matching function for call to 'std::map<int, int (*)(int, int)>::insert(int, int (*)(int, int))'. Please note the identical signature (int, int (*)(int, int)) on both sides of the error message.
My questions are,
Is it a sound approach to use std::map for the described purpose?
Why does the sample code throw an error, and obviously
How to correct the code?
Although having >40y of programming experience, I am quite new to C++ and for sure I am missing some basic aspect here. Can you please point me into the right direction?
Thanks!
#include <map>
typedef int (*t_handler)(int,int);
// Gives the same result: using t_handler = int (*)(int,int);
int product(int u, int v) {
return u*v;
}
// Map numeric ID to a function
std::map<int, t_handler> myMap;
int main() {
// Define 100 as the function to calculate the product
myMap.insert(100, &product); // prog.cc:16:17: error: no matching function for call to 'std::map<int, int (*)(int, int)>::insert(int, int (*)(int, int))'
// Calculate 5*8
int x = myMap[100](5, 8);
return 0;
}
insertagain, with particular attention given to the argument type. The error message is telling you that the function you are trying to call doesn't exist. It's a little opaque because there are a bunch of overloads forinsert, some of which take two arguments.std::unordered_map<int, std::function<int(int, int)>>should be more handy.