Passing a function as an argument with a return value for the template

I have a C ++ function that looks like this:

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 call it from the outside as follows

 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 an error

 template parameter T is ambigious 

I assume the problem is combining the template and passing the function as an argument, but I'm not sure how to figure it out. (I do not want to write a function twice with only different types). Any solution?

+5
source share
1 answer

The error message indicates that the template argument for T is output inconsistently - i.e. the return type fn and type num are different in the second code fragment.

This can be solved in several ways, of which the following 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 easier,

 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; } 
+1
source

Source: https://habr.com/ru/post/1216553/


All Articles