我想访问一个通过在运行时根据输入定义的指针返回一对的函数。
示例代码:
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如下所示,位于名称空间“ Math”中:
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的左值”。当calcSpeed返回双精度值时,上面的代码运行良好-该方法是否与返回双精度函数不兼容,如果是,是否存在不涉及将函数的返回类型从双精度变为其他函数的变通办法?
我想在运行时分配指针的原因是,我可以根据输入选择是使用CalcSpeed还是使用具有相同参数和返回类型的许多其他函数,而没有条件的唯一方法是通过此方法(我思考)。
提前致谢,
编辑:完整错误代码仅供参考:
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:
我忘了包含我的代码行,它可以解决这个问题。下面的答案表明问题出在typedef中的'struct strinfo * si'-应该是'Math :: strinfo * si'。
您要声明一个新类型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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句