将函数作为带有模板返回值的参数传递
Passing function as argument with template return value
我有一些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;
}
相关文章:
- void 函数可以传递值参数吗?
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 将输入参数作为右值引用传递?
- 如何在另一个函数中使用返回值作为参数?
- 如何将一个函数的返回值作为另一个函数的参数传递?
- 参数传递和返回值如何在程序集级别的 x86 上的 C/C++ 中工作?
- 将指向数组的指针作为函数参数传递,这本身就是另一个函数的返回值?
- C++ ReSharper - 生成函数返回值/参数类型的变量
- 数组在函数中作为参数传递并被访问,那么为什么从函数返回后数组的值会被修改呢?
- 将函数返回值传递给引用参数会导致 GCC 中的编译错误
- 将函数作为带有模板返回值的参数传递
- 是指向在向函数返回值/参数和类请求传输数据期间复制的内存的指针
- 常量参数与右值参数传递,当内部保存到类私有变量时
- 将构造函数的返回值作为参数传递
- 我可以从引用传递的参数返回值中声明const int吗
- 返回布尔函数的值,并将指针作为参数传递
- 为什么在将对象作为按值参数传递给方法时调用复制构造函数?
- 如何将返回函数中的值作为另一个函数的参数传递,在c++中使用它,然后适当地调用它
- 返回值或修改引用传递的参数是否更快?
- 可变模板与模板函数名和传递参数和返回值