cpp-lambda

Lambda Function

construct a closure: an unnamed function object capable of capturing variables in scope. 

Syntax

[ capture-list ] ( params ) { body }


[ capture-list]:Capture list can be passed as follows (see below for the detailed description):
                   1.[a,&b] where a is captured by value and b is captured by reference.
                2.[this] captures the this pointer by value
                3.[&] captures all automatic variables odr-used in the body of the lambda by reference
                4.[=] captures all automatic variables odr-used in the body of the lambda by value
                5.[] captures nothing

Delegates and Lambda

What is delegate?
now let’s look at an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <functional>
#include <string>
class EmailProcessor
{
public:
void receiveMessage (const std::string& message)
{
if ( _handler_func )
{
_handler_func( message );
}
}
void setHandlerFunc (std::function<void (const std::string&)> handler_func)
{
_handler_func = handler_func;
}
private:
std::function<void (const std::string&)> _handler_func;
};

let’s say we want another class that keeps track of the longest message received so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class MessageSizeStore
{
public:
MessageSizeStore () : _max_size( 0 ) {}
void (const std::string& message )
{
const int size = message.length();
if ( size > _max_size )
{
_max_size = size;
}
}
int getSize ()
{
return _max_size;
}
private:
int _max_size;
};

with lambda functions we can easily bind var size_store into the function passed into setHandlerFunc

1
2
3
4
5
EmailProcessor processor;
MessageSizeStore size_store;
processor.setHandlerFunc(
[&] (const std::string& message) { size_store.checkMessage( message ); }
);