Reputation: 111
I want to access a function that returns a pair through a pointer that is defined according to input at runtime.
Example code:
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 looks like this and is in the namespace '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));
}
}
I can't assign FuncChosen p to calcSpeed because it has an 'lvalue of type std::pair'. The code above worked fine when calcSpeed returned a double - is this method incompatible with functions that return a pair and if so are there any workarounds that don't involve changing the return type of the function from a pair to something else?
The reason I want to assign the pointer at runtime is so that I can choose whether to use calcSpeed or a number of other functions with same parameters and return types according to input and the only way to do this without conditionals is by this method (I think).
Thanks in advance,
Edit: Full error code 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 *'))
Edit 2:
I forgot to include a line of my code that would have given away the problem. The answer below shows the problem was with 'struct strinfo *si' in the typedef - should be 'Math::strinfo *si'.
Upvotes: 1
Views: 330
Reputation: 109119
You're declaring a new type named strinfo
in your typedef
typedef std::pair<double, string> (*FuncChosen)(struct strinfo *si, double first, double second);
// ^^^^^^^^^^^^^^^^
// that's a declaration of new type, not Math::strinfo
The error would've been obvious if you'd omitted the unnecessary struct
keyword in the typedef
. Change it to
typedef std::pair<double, std::string> (*FuncChosen)(Math::strinfo *si, double first, double second);
or the (IMHO) more readable version
using FuncChosen = std::pair<double, std::string>(*)(Math::strinfo *si, double first, double second);
Upvotes: 2