Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ map of cmath functions

Tags:

c++

function

map

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

like image 946
Muckle_ewe Avatar asked Oct 04 '22 19:10

Muckle_ewe


1 Answers

typedef double (*DoubleFuncPtr)(double);
...
funcMap.insert( std::make_pair( "sqrt", static_cast<DoubleFuncPtr>(std::sqrt) ) );
like image 50
catscradle Avatar answered Oct 07 '22 19:10

catscradle