将函数作为带有模板返回值的参数传递

Passing function as argument with template return value

本文关键字:返回值 参数传递 函数      更新时间:2023-10-16

我有一些c++函数,如下所示:

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;
 }

我以以下方式从外面叫它

double num = 0.45;
double (*fn)(QString, bool) = &doubleFromString;
function(&text, num, fn);

和(编辑)

unsigned int num = 5;
int (*fn)(QString, bool) = &intFromString;
function(&text, num, fn);

我得到错误

template parameter T is ambigious

我想问题出在将模板和传递函数作为参数的组合上,但我不知道如何解决这个问题。(我不想仅仅用不同的类型编写两次函数)。有什么解决方案吗?

错误消息表明T的模板参数推导不一致,即返回的fn类型和num类型在第二个代码片段中不同。

这可以通过几种方式解决,其中以下一种可能是最简单的:

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;
 }

或者,比这更简单的

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;
 }