5
votes

I would like to create a map with the keys being a function name as a string and the value being the function itself. So something like this...

#include <cmath>
#include <functional>
#include <map>
#include <string>

typedef std::function<double(double)> mathFunc;

int main() {
    std::map< std::string, mathFunc > funcMap;

    funcMap.insert( std::make_pair( "sqrt", std::sqrt ) );

    double sqrt2 = (funcMap.at("sqrt"))(2.0);

    return 0;
}

would be used to call the sqrt function on some input value. Then of course you could add other functions to the map like sin, cos, tan, acos, etc, and just call them by some string input. My problem here is to what the value type should be in the map, both function pointers and std::function give the following error at the std::make_pair line

error: no matching function for call to 'make_pair(const char [5], <unresolved overloaded function type>)'

So what should my value type be for built in functions like std::sqrt?

Thanks

2
They're overloaded. How can it tell which one to use?chris
Surely I can specify that the signature should be double(double) somehow? Even doing std::make_pair<std::string, mathFunc> gives the same error. I take it you meant how there is 4 different types, as from cplusplus.com/reference/cmath/sqrt?Muckle_ewe
You can cast the function.chris

2 Answers

4
votes
typedef double (*DoubleFuncPtr)(double);
...
funcMap.insert( std::make_pair( "sqrt", static_cast<DoubleFuncPtr>(std::sqrt) ) );
0
votes

You can use a typedef for a function pointer and since its a map you can use operator[] to insert the function:

typedef double(*mathFunc)(double);

...

funcMap[std::string( "sqrt")]= std::sqrt;

...

Code at ideone

You will need some other maps for functions which do not take a single double as parameters.