lambda expressions --C ++ 11 (fourteen)

[&] ( Int A) { return A < x;}  
 // where x is a local scope where the variable lambda expressions, and hereby is captured.
// [&] is a list of capture, which states that all local name (such as x) lambda used to access by reference.
// If only want to capture x, can be written as [x &]
 // If desired object generation function to pass a copy of x, then written as [x =]
 // capture all local name used to access the values of the [=]
 / / nothing capture is [] 

// specific application example 
Template <typename C, typename Oper> void for_all (C & C, Oper OP) 
{ for (Auto & X: C) 
        OP (X); 
} 
Vector <a unique_ptr <the Shape> > V; 
for_all (V, [] (a unique_ptr <the Shape> & PS) {the PS-> Draw ();});

    Perform a specific operation for each object element pointer points to the container 
for_all (V, [] (a unique_ptr <the Shape> & PS) {the PS-> Rotate ( 45 );}); 

// the lambda represents a generic 
Template < class S >
 void rotate_add_draw (Vector <S> & V, int R & lt) 
{ 
    for_all (V, [] (Auto & S) S- {> Rotate (R & lt); S-> Draw ();}); 
} 

Vector <* the Shape > V2; 
rotate_add_draw (V2, 90 );

 

Guess you like

Origin www.cnblogs.com/share-ideas/p/11921245.html