【问题标题】:C++ map of cmath functionscmath 函数的 C++ 映射
【发布时间】:2013-06-17 01:52:17
【问题描述】:

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

#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::function 在 std::make_pair 行都给出以下错误

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

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

谢谢

【问题讨论】:

  • 他们超载了。它如何判断使用哪一个?
  • 我当然可以指定签名应该是双(双)以某种方式?即使做 std::make_pair<:string mathfunc> 也会出现同样的错误。我认为你的意思是有 4 种不同的类型,从 cplusplus.com/reference/cmath/sqrt?
  • 你可以强制转换函数。

标签: c++ function map


【解决方案1】:
typedef double (*DoubleFuncPtr)(double);
...
funcMap.insert( std::make_pair( "sqrt", static_cast<DoubleFuncPtr>(std::sqrt) ) );

【讨论】:

  • 是的,这很好用,所以我猜问题出在数学函数重载,而静态转换可以解决这个问题。
【解决方案2】:

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

typedef double(*mathFunc)(double);

...

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

...

代码ideone

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

【讨论】:

    猜你喜欢
    • 2012-06-17
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 2014-09-03
    • 2011-06-01
    相关资源
    最近更新 更多