What does [=] mean in C ++?

I want to know what [=] does? Here is a quick example

 template <typename T> std::function<T (T)> makeConverter(T factor, T offset) { return [=] (T input) -> T { return (offset + input) * factor; }; } auto milesToKm = makeConverter(1.60936, 0.0); 

How will the code work with [] instead of [=] ?

I suppose that

 std::function<T (T)> 

means a prototype function that takes (T) as an argument and returns a type T ?

+84
c ++ lambda c ++ 11
Jan 13 '16 at 22:08
source share
2 answers

[=] you are talking about is part of the capture list for lambda expression. This tells C ++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables that it uses when creating it. This is necessary so that the lambda expression can refer to factor and offset , which are local variables inside the function.

If you replace [=] with [] , you will get a compiler error because the code inside the lambda expression will not know what the offset and factor variables mean. Many compilers give good diagnostic error messages if you do, so try and see what happens!

+100
Jan 13 '16 at 10:11
source share

This is a lambda capture list. Makes variables available for lambda. You can use [=] , which copies by value, or [&] , which follows the link.

+37
Jan 13 '16 at 10:11
source share



All Articles