【发布时间】:2019-01-20 20:02:07
【问题描述】:
当我使用接受另一个函数作为参数的模板函数时,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)。
【问题讨论】:
标签: c++ c++11 templates template-argument-deduction type-deduction