Monday, April 8, 2013

C++11 : Auto, Lambda Expression and decltype


Auto keyword

int x = 3;
auto y = x;

The compiler will deduce that y is an int. This, of course, isn't a shining example of where auto is really useful. 
Auto really comes into its own when working with templates and especially the STL.
Now take another example, you want to iterate over a vector. So for that, you need an iterator:
map<string, string>::iterator itr = address_book.begin(); 

This above declaration is somewhat looking weird. Simply you can write the above statement as:  
auto itr = address_book.begin();

Lambda Functions  


C++11 provides support for anonymous functions, called lambda functions.  
Syntax:-
[capture](parameters)->return-type{body}

If there are no parameters the empty parentheses can be omitted.
[capture]->return-type{body}

The return type can often be omitted, if the body consists only of one return statement or the return type is void.
[capture](parameters){body} 

[]        //no variables defined. Attempting to use any external variables in the lambda is an error.
[x, &y]   //x is captured by value, y is captured by reference 
[&]       //any external variable is implicitly captured by reference if used 
[=]       //any external variable is implicitly captured by value if used
[&, x]    //x is explicitly captured by value. Other variables will be captured by reference.
[=, &z]   //z is explicitly captured by reference. Other variables will be captured by value.
[this]  //Capture the this pointer of the enclosing class

For example:-
Example 1:-
int main()
{
    int x = 5;
    int y;
    auto func = [=,&y](){y=x;};//x is read only(=), y is reference(&)
    func();
   return 0;
}

Example 2:-
class Foo
{
public:
    Foo () : _x( 3 ) {}
    void func ()
    {
        // a very silly, but illustrative way of printing out the value of _x
        [this] () { cout << _x; } ();
    }

private:
        int _x;
};

Decltype

Now, the question arising in your mind is that, if we didn't explicitly provide the return type then, how the compiler knows about the return type.
So, there is an another C++11 feature by which the compile extract the return type information,
i.e; decltype() 

Auto lets you declare a variable with a particular type; decltype lets you extract the type 
from a variable (or any other expression). 
For example:-

int x = 3;
decltype(x) y = x; //decltype(x) will extract the return type of x

The above example is the simple one.
Now, Let we talk in terms of lambda, means where it is used. So check this example:-
[](int x, int y) { return x + y; } // implicit return type from 'return' statement

The return type of this unnamed function is decltype(x+y). The return type can be omitted if the lambda function is of the form return expression(i.e.;[](int x, int y)->int), or if all locations that return a value return the same type when the return expression is passed through decltype.

No comments:

Post a Comment