首页 > 解决方案 > 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 + 1int,所以它应该推断出T = int)。

标签: c++c++11templatestemplate-argument-deductiontype-deduction

解决方案


模板参数必须出现在函数参数类型中才能扣除。此外,lambda 不是函数,因此,无论 lambda 的返回类型如何,都不能参与模板参数推导。

但是在这种情况下,不需要指定返回类型。返回类型扣除可以做的工作:

template <typename S, class Functor>
auto applyFun(const S& source, const Functor& f) {
  return f(source);
  }

推荐阅读