Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [=] mean in C++?

Tags:

c++

c++11

lambda

I want to know what [=] does? Here's a short 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 would the code work with [] instead of [=]?

I assume that

std::function<T (T)> 

means an function prototype which gets (T) as argument and return type T?

like image 279
der_lord Avatar asked Jan 13 '16 22:01

der_lord


People also ask

What does =! Mean in C?

It could be a mistyping of the != operator, meaning not equal to. Example: if (a != b) { // a is not equal to b } It could be a mistyping a == ! b , meaning a is equal to not b , which would most commonly be used with booleans.

What does [&] mean in C++?

It's a lambda capture list and has been defined in C++ from the C++11 standard. [&] It means that you're wanting to access every variable by reference currently in scope within the lambda function.

What is a lambda in C?

Lambda Function − Lambda are functions is an inline function that doesn't require any implementation outside the scope of the main program. Lambda Functions can also be used as a value by the variable to store. Lambda can be referred to as an object that can be called by the function (called functors).

What is the return type of lambda?

The return type for a lambda is specified using a C++ feature named 'trailing return type'. This specification is optional. Without the trailing return type, the return type of the underlying function is effectively 'auto', and it is deduced from the type of the expressions in the body's return statements.


1 Answers

The [=] you're referring to is part of the capture list for the 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 it uses when it's created. This is necessary for the lambda expression to be able to refer to factor and offset, which are local variables inside the function.

If you replace the [=] with [], you'll get a compiler error because the code inside the lambda expression won't know what the variables offset and factor refer to. Many compilers give good diagnostic error messages if you do this, so try it and see what happens!

like image 68
templatetypedef Avatar answered Sep 28 '22 16:09

templatetypedef