c++的cmath函数映射



我想创建一个映射,其中键是函数名称作为字符串,值是函数本身。所以像这样的…

#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;
}

将用于对某个输入值调用SQRT函数。当然,你可以在映射中添加其他函数,比如sin cos tan acos等等,然后通过字符串输入调用它们。我这里的问题是映射中的值类型应该是什么,函数指针和std::函数都在std::make_pair行

处给出以下错误
error: no matching function for call to 'make_pair(const char [5], <unresolved overloaded function type>)'

那么对于像std::sqrt这样的内置函数,我的值类型应该是什么?

谢谢

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

你可以使用typedef函数指针,因为它是一个映射,你可以使用操作符[]来插入函数:

typedef double(*mathFunc)(double);
...
funcMap[std::string( "sqrt")]= std::sqrt;
...

ideone代码

对于不以单个double作为参数的函数,您将需要一些其他映射

最新更新