C++ 11 lambda和模板专业化

Jar*_*sie 3 c++ lambda templates c++11

我想知道下面给出的lambda的正确类型定义是什么,以便下面的代码将使用符合条件的c ++ 11编译器进行编译:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我想另一种可以做到的方式是这样的:

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;
}
Run Code Online (Sandbox Code Playgroud)

Xeo*_*Xeo 15

它是auto+ decltype:

auto l = [](int i) -> bool { printf("%d",i); return true; };
foo<decltype(l)> fi(l);
fi.fum();
Run Code Online (Sandbox Code Playgroud)

每个lambda都有一个不同的,唯一的,未命名的类型.作为一名程序员,你无法命名.

但是,在你的情况下,由于lambda不捕获任何东西(空[]),它可以隐式转换为指向函数的指针,所以这样做:

foo<bool(*)(int)> fi([](int i) -> bool { printf("%d",i); return true; });
fi.fum();
Run Code Online (Sandbox Code Playgroud)


Ker*_* SB 7

是的std::function<bool(int)>.或者可能只是bool(*)(int)你喜欢,因为lambda没有捕获.

(原始函数指针可能更有效,因为std::function(至少在某些情况下)需要动态分配某些类型的擦除魔法.)