c++ - C++ 不能为高阶函数派生模板参数
问题描述
当我使用接受另一个函数作为参数的模板函数时,C++ 无法派生模板参数。一直指定它们非常烦人。如何定义以下函数,这样我就不必每次都指定类型参数?
#include <functional>
template <typename S, typename T>
T apply(const S& source, const function<T (const S&)>& f) {
return f(source);
}
template <typename S, class Functor, typename T>
T applyFun(const S& source, const Functor& f) {
return f(source);
}
int main() {
// Can't derive T. Why?
apply(1, [](int x) { return x + 1; });
// Compiles
apply<int, int>(1, [](const int& x) { return x + 1; });
// Can't derive T. Kind of expected.
applyFun(1, [](int x) { return x + 1; });
}
对我来说,为什么它不能在第二个函数中派生类型参数而不是在第一个函数中是有道理的(因为x + 1
是int
,所以它应该推断出T = int
)。
解决方案
模板参数必须出现在函数参数类型中才能扣除。此外,lambda 不是函数,因此,无论 lambda 的返回类型如何,都不能参与模板参数推导。
但是在这种情况下,不需要指定返回类型。返回类型扣除可以做的工作:
template <typename S, class Functor>
auto applyFun(const S& source, const Functor& f) {
return f(source);
}
推荐阅读
- php - 我试图下载图像,但我只得到一张图像
- r - 抵消 GLM 因子 R - 标准误差
- html - 如何防止 div 在小屏幕 Bootstrap 中进入另一个 div
- sql - postgresql,根据条件获取数据
- javascript - 在 AWS Lambda 中使用 JSON 对象请求数据时出现 CORS 错误
- javascript - VueJS @click 传递数据
- docker - 无法使用自定义配置挂载 Nginx 容器
- angular - 如何从放置请求角度检查返回值
- python - 无法通过 kivy 应用程序中的屏幕管理器添加新屏幕
- c# - 如何在控制器中返回员工列表,给定一个布尔参数,fx api/employees?hasOvertime=true