Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 define function type capture by reference

Tags:

c++

c++11

How do I turn below function into a typedef?

auto fn = [&] (int x) { doSomething(x, 3); }
like image 600
linquize Avatar asked Aug 31 '13 14:08

linquize


People also ask

What is the syntax of defining lambda expression in C++11?

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.

How do you declare a lambda in C++?

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 a lambda closure be used to create a C++11 thread?

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.

When should I use lambdas C++?

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.


2 Answers

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).

like image 125
mavam Avatar answered Oct 05 '22 23:10

mavam


How about

using my_function_type = std::function<void(int)>;
like image 27
Some programmer dude Avatar answered Oct 06 '22 00:10

Some programmer dude