考虑以下几点:如何用lambda函数作为参数传递模板函数中的函数类型参数?
#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
}
,因为编译器不能推断这是作为参数传递的拉姆达类型int(&)(int)
的p3
声明失败。 p1
是可以的,因为类型可以很容易地从函数foo
得到,p2
也可以,因为类型是显式声明的。
它失败:
error: invalid use of incomplete type 'class C<main()::<lambda(int)> >'
有什么办法使编译器corretly推断函数类型,给出一个lambda?
P.S .: C++ 17答案也可以,如果适用的话。
http://stackoverflow.com/questions/21657627/what-is-the-type-signature-of-a-c11-1y-lambda-function – LogicStuff