How do I turn below function into a typedef?
auto fn = [&] (int x) { doSomething(x, 3); }
Creating a Lambda Expression in C++auto greet = []() { // lambda function body }; Here, [] is called the lambda introducer which denotes the start of the lambda expression. () is called the parameter list which is similar to the () operator of a normal function.
C++ 11 introduced lambda expressions to allow inline functions which can be used for short snippets of code that are not going to be reused and therefore do not require a name. In their simplest form a lambda expression can be defined as follows: [ capture clause ] (parameters) -> return-type { definition of method }
Can you create a C++11 thread with a lambda closure that takes a bunch of arguments? Yes – just like the previous case, you can pass the arguments needed by the lambda closure to the thread constructor.
We have seen that lambda is just a convenient way to write a functor, therefore we should always think about it as a functor when coding in C++. We should use lambdas where we can improve the readability of and simplify our code such as when writing callback functions.
You can use decltype
to get the exact type:
auto fn = [&] (int x) { doSomething(x, 3); };
using lambda_type = decltype(fn);
But if you merely want to know a compatible, more general type, say for passing the lambda as argument to another function, you can use std::function<void(int)>
(as Joachim mentions).
How about
using my_function_type = std::function<void(int)>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With