I can declare anonymous functions (they are the same as lambda, but without "context" - [...]
) without auto
easily:
#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;
}
But how to declare lambda ? Is it the only possible way? (maybe with typedef). Here I use ::std::function
, but I didn't mention context of f somewhere in foo arguments...:
#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;
}