Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing function as argument with template return value

Tags:

c++

templates

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?

like image 207
TinF Avatar asked Nov 10 '22 16:11

TinF


1 Answers

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;
 }
like image 129
Columbo Avatar answered Nov 15 '22 06:11

Columbo