yan*_*pas 2 c++ lambda pointers anonymous-function auto
我可以轻松地声明匿名函数(它们与lambda相同,但没有"context" - [...])auto:
#include <iostream>
using namespace ::std;
void foo(void (*f)(char))
{
f('r');
}
int main()
{
void (*anon)(char) = [](char c) -> void { cout << c << endl; };
foo(anon);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是如何宣布lambda?这是唯一可能的方式吗?(也许使用typedef).我在这里使用::std::function,但我没有在foo参数中提到f的上下文...:
#include <iostream>
#include <functional>
using namespace ::std;
//int foo(auto f, char x) // !only since c++14
int foo(function<int(char)> f, char x)
{
return f(x+1);
}
int main()
{
int a = 5, b = 10;
//void (*lambda)(char) = [](char c) { cout << c << endl; };
//auto sample_lambda = [&a,b](char c) -> int // !only since c++11
function<int(char)> sample_lambda = [&a,b](char c) -> int
{
for (;a<b;a++)
cout << a << c << endl;
return (int)c+a;
};
foo(sample_lambda, 's');
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你不能.
闭包的类型是一种唯一的,未命名的类型.你的第一个例子是有效的,因为闭包类型有一个转换函数指向函数的指针,如果它们没有捕获任何东西,不是因为闭包是一个void (*) (char).
您最好坚持使用,auto因为std::function类型擦除会产生额外的开销.