【发布时间】:2016-12-28 11:45:56
【问题描述】:
考虑以下几点:
#include <utility>
#include <string>
template<typename>
class C;
template<typename R, typename T>
class C<R(&)(T)> {
public:
template<typename F>
C(F&& fun) {}
};
template<typename T>
C<T> makeC(T&& fun) {
return C<T>(std::forward<T>(fun));
}
int foo(int a){return a;}
int main() {
auto p1 = makeC(foo); // OK
auto p2 = C<int(&)(int)>([](int a){return a;}); // OK
// auto p3 = makeC([](int a){return a;}); // FAIL
}
p3 的声明失败,因为编译器无法从作为参数传递的 lambda 推断类型 int(&)(int)。 p1 可以,因为可以从函数foo 轻松推断出类型,而p2 可以,因为类型是显式声明的。
它失败了:
error: invalid use of incomplete type 'class C<main()::<lambda(int)> >'
有没有办法让编译器在给定 lambda 的情况下正确推断函数类型?
P.S.:如果适用,C++17 的答案也可以。
【问题讨论】:
标签: c++ templates lambda c++14 type-inference