创建一个指向返回std :: pair的函数的成员函数指针

时间:2014-11-05 20:18:11

标签: c++ pointers c++11 std-pair

我想访问一个函数,该函数通过在运行时根据输入定义的指针返回一对。

示例代码:

int main() {
    struct Math::strinfo si; // This was what caused the problem - See answer and question edit

    typedef std::pair<double, string> (*FuncChosen)(struct strinfo *si, double first, double second);
    FuncChosen p = Math::calcSpeed;
}

calcSpeed看起来像这样,位于名称空间&#39; Math&#39;:

namespace Math {
    struct strinfo
    {
        string strformula;
        string chosenCalcStr;
    };

    std::pair<double, string> calcSpeed(struct strinfo *si, double distance, double time)
    {
        si->strformula = "Speed = distance / time";
        si->chosenCalcStr = "Speed";
        return make_pair(distance/time, std::to_string(distance) + " / " + std::to_string(time));
    }
}

我无法将FuncChosen p指定给calcSpeed,因为它有一个类型为std :: pair&#39;的左值。 当calcSpeed返回一个double时,上面的代码运行正常 - 这个方法与返回一对的函数不兼容,如果有的话,是否有任何变通方法不涉及将函数的返回类型从一对更改为其他东西?< / p>

我想在运行时分配指针的原因是我可以选择是否使用calcSpeed或许多其他具有相同参数的函数并根据输入返回类型,并且没有条件的唯一方法就是这样做方法(我认为)。

提前致谢,

编辑: 完整错误代码FYI:

SDT_Test/main.cpp:63:16: Cannot initialize a variable of type 'FuncChosen' (aka 'std::pair<double,   string> (*)(struct strinfo *, double, double)') with an lvalue of type 'std::pair<double, string> (struct strinfo *, double, double)': type mismatch at 1st parameter ('struct strinfo *' (aka 'strinfo *') vs 'struct strinfo *' (aka 'Math::strinfo *'))

编辑2:

我忘了包含一行代码来解决这个问题。下面的答案表明问题出在&#39; struct strinfo * si&#39;在typedef中 - 应该是&#39; Math :: strinfo * si&#39;。

1 个答案:

答案 0 :(得分:2)

您在strinfo

中声明了名为typedef的新类型
typedef std::pair<double, string> (*FuncChosen)(struct strinfo *si, double first, double second);
//                                              ^^^^^^^^^^^^^^^^ 
// that's a declaration of new type, not Math::strinfo

如果您在struct中省略了不必要的typedef关键字,则该错误很明显。将其更改为

typedef std::pair<double, std::string> (*FuncChosen)(Math::strinfo *si, double first, double second);

或(IMHO)更易阅读的版本

using FuncChosen = std::pair<double, std::string>(*)(Math::strinfo *si, double first, double second);
相关问题