‘auto’ Keyword in Visual C++ 2010

Starting with Visual C++ 2010, the ‘auto’ keyword has a different meaning. Auto is now used as a variable type and it instructs the compiler to figure out the exact type itself. This makes it much easier to define function pointers or to iterate over vectors for example. This post will give a brief overview of how to use the ‘auto’ keyword.

Suppose we have the following map that maps integers to vectors of strings of type TCHAR:

map<int, vector< basic_string<TCHAR> > > myMap;

The usual way to iterate over the map and print the contents would be something like the following:

for (map<int, vector< basic_string<TCHAR> > >::const_iterator citer = myMap.begin();
        citer != myMap.end(); ++citer)
{
    tcout << _T("Map element ") << (*citer).first << _T(": ");
    for (vector< basic_string<TCHAR> >::const_iterator citer2 = (*citer).second.begin();
            citer2 != (*citer).second.end(); ++citer2)
    {
        tcout << _T("'") << (*citer2) << _T("', ");
    }
    tcout << endl;
}

Now, instead of using the explicit type of the iterator, lets use the new ‘auto’ keyword.

for (auto citer = myMap.begin(); citer != myMap.end(); ++citer)
{
    tcout << _T("Map element ") << (*citer).first << _T(": ");
    for (auto citer2 = (*citer).second.begin(); citer2 != (*citer).second.end(); ++citer2)
    {
        tcout << _T("'") << (*citer2) << _T("', ");
    }
    tcout << endl;
}

Using the ‘auto’ keyword makes the for lines much less complicated and easier to read.

We can even go one step further and combine the ‘auto’ keyword with the ‘for each’ contruct as follows:

for each (auto m in myMap)
{
    tcout << _T("Map element ") << m.first << _T(": ");
    for each(auto e in m.second)
    {
        tcout << _T("'") << e << _T("', ");
    }
    tcout << endl;
}

This makes reading the for loops even more easier 🙂

The ‘auto’ keyword can also be used for function pointers as demonstrated below. Suppose we have the following function that prints out the contents of our map.

const vector< basic_string<TCHAR> >* PrintContents(const map<int, vector< basic_string<TCHAR> > >& theMap)
{
    /* print contents of the map */
    return NULL;
}

The function accepts a reference to a map that maps integers to vectors of strings of type TCHAR. The function returns a pointer to a vector of strings of type TCHAR. Creating a function pointer and calling the function through that pointer required something like the following:

const vector< basic_string<TCHAR> >* (*p)(const map<int, vector< basic_string<TCHAR> > >&) = &PrintContents;
p(myMap);

With the ‘auto’ keyword this can be simplified to:

auto f = &PrintContents;
f(myMap);

More information about the ‘auto’ keyword can be found on this MSDN page.

The Visual Studio 2010 project below is a demo application of the above explanation.

AutoTypeDeductionDemo.zip

Share

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment: