简体   繁体   中英

C++ map of cmath functions

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM