【发布时间】:2016-07-29 22:13:05
【问题描述】:
我有以下功能:
template <class InType, class OutType>
OutType foo(const InType &a, std::function<OutType (const InType &)> func)
{
return func(a);
}
template <class T>
T bar(T a, T b)
{
return a + b;
}
我可以这样称呼他们:
double x = foo<int, double>(1, [] (const int &v) { return float(v) * 1.5f; });
double y = bar<int>(1.0, 2.0);
...并使用带 bar 的模板参数推导
double z = bar(1.0, 2.0);
...但是如果我尝试对 foo 使用模板参数推导:
double w = foo(1, [] (const int &v) { return float(v) * 1.5f; });
失败并出现此错误:
no matching function for call to 'foo'
double w = foo(1, [] (const int &v) { return float(v) * 1.5f; });
^~~
note: candidate template ignored: could not match 'function<type-parameter-0-1 (const type-parameter-0-0 &)>' against '(lambda at ../path/to/file.cpp:x:y)'
OutType foo(const InType &a, std::function<OutType (const InType &)> func)
^
这是为什么呢?从我的角度来看,很明显应该将参数类型推断为什么。
【问题讨论】:
标签: c++ templates template-argument-deduction