C ++ 11 lambda和模板专门化 [英] C++11 lambda and template specialization
本文介绍了C ++ 11 lambda和模板专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道下面的lambda是什么是正确的类型定义,所以下面的代码将使用符合的c ++ 11编译器编译:
I would like to know what is the correct type definition for the lambda presented below, so that the following code will compile using a conformant c++11 compiler:
#include <cstdio>
#include <string>
template<class Func>
class foo
{
public:
foo(Func func)
: fum(func){}
Func fum;
};
int main()
{
foo<???> fi([](int i) -> bool { printf("%d",i); return true; });
fi.fum(2);
return 0;
}
我猜想另一种方法是这样的:
I guess another way it could be done is like so:
template<typename Func>
foo<Func> make_foo(Func f)
{
return foo<Func>(f);
}
int main()
{
auto fi = make([](int i) -> bool { printf("%d",i); return true; });
fi.fum(2);
return 0;
}
推荐答案
> auto + decltype
:
auto l = [](int i) -> bool { printf("%d",i); return true; };
foo<decltype(l)> fi(l);
fi.fum();
每个lambda都有不同的,唯一的,未命名的类型。
Every single lambda has a different, unique, unnamed type. You, as a coder, just can not name it.
但是,在你的情况下,因为lambda不捕获任何东西(空的) []
),它可以隐式转换为指向函数的指针,因此这样做:
However, in your case, since the lambda doesn't capture anything (empty []
), it is implicitly convertible to a pointer-to-function, so this would do:
foo<bool(*)(int)> fi([](int i) -> bool { printf("%d",i); return true; });
fi.fum();
这篇关于C ++ 11 lambda和模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文