Reputation: 89
I have some c++ function that looks like follows:
template<class T> bool function(QString *text, T number, T (*f)(QString, bool)){
bool ok = true;
QString c = "hello";
T col = (*f)(c, &ok);
// do something with col here ...
return true;
}
I am calling it from outside in following manner
double num = 0.45;
double (*fn)(QString, bool) = &doubleFromString;
function(&text, num, fn);
and (Edited)
unsigned int num = 5;
int (*fn)(QString, bool) = &intFromString;
function(&text, num, fn);
And I get error
template parameter T is ambigious
I guess that problem is in combining template and passing function as argument, but I am not sure how to figure that out. (I don't want to write the function twice just with different types). Any solution?
Upvotes: 5
Views: 132
Reputation: 60999
The error message indicates that the template argument for T
is deduced inconsistently - i.e. the returned type of fn
and the type of num
differ in your second code snippet.
This can be solved in several ways, of which the following one is perhaps the simplest:
template<class T, class R>
bool function(QString *text, T number, R (*f)(QString, bool)) {
// [..]
T col = f(c, &ok); // Cast if necessary. Dereferencing is superfluous, btw.
// [..]
return true;
}
Or, even simpler than that,
template<class T, class F>
bool function(QString *text, T number, F f) {
bool ok = true;
QString c = "hello";
T col = f(c, &ok);
// [..]
return true;
}
Upvotes: 1