Home > C++, VC++, Visual studio > auto keyword redefined in VC10

auto keyword redefined in VC10

auto keyword is one of those keywords that’s never used. So what the c++ committee has done is, they’ve started using it for a better purpose. For better understanding see this simple demo…

First without using auto keyword…

void AutoTest()
{
  typedef std::vector<int> IntVector;
  IntVector Ints;
  std::generate_n(std::back_inserter( Ints ), 100, rand);

  // After filling some elements into the vector, we iterate through them
  for( IntVector::iterator Itr = Ints.begin(); Itr != Ints.end(); ++Itr )
  {
    // Some code
  }
}

Now let’s try with the auto keyword…

void AutoTest()
{
  typedef std::vector</int><int> IntVector;
  IntVector Ints;
  std::generate_n(std::back_inserter( Ints ), 100, rand);

  // After filling some elements into the vector, we iterator through them
  for( auto Itr = Ints.begin(); Itr != Ints.end(); ++Itr )
  {
    // Some code
  }
}

Hope you noticed the difference, the type for the variable Itr is automagically inferred by the compiler based on the return type from Ints.begin().  Another huge benefit is when using auto keyword to wrap a lamda  expression (an anonymous/inline functor). See this example…

void LamdaTest()
{
int x = 0;
auto LamdaFunc = [&x](int y)
{
while( y– > 0 )
{
++x;
}
};

LamdaFunc( 10 );
LamdaFunc( 100 );

std::cout < < "Value of x after calling LamdaFunc is: " << x; }[/sourcecode] For us it's hard to infer or to know how to declare the type of this lamda expression but for the compiler it's easy (well hope so). When we give auto keyword the type is auto inferred. We then use LamdaFunc object to invoke this lamda expression. In the end x will have the value 110. Note that the expression [&x] means, pass x by reference. I'll brag about lamda's in my next post probably. Cool isn't it, I liked this feature. 8)

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: