Type inference in C++

The new C++0x standard provides support for type inference. The auto keyword that was doing nothing in C++ was given a new meaning: a placeholder for a type inferred by the compiler. For those familiar with C#’s var keyword, this is basically the same.

Here is a comparison between auto in C++ and var in C#.

C++ C#

with the output

C++ C#

As you can see, the use is very similar, except that in C++ you can use auto for a lambda expression, while in C# you cannot. The C# compiler raises an error, CS0815, when you try to use var with an anonymous function expressions, a lambda expression, a method group expressions, or the null literal expression, because these don’t have a type.

Just like with var, you can only use auto locally, and not as return type from a function, or parameter to a function.

While it might not be of that much help for ints or strings, using auto for instead of vector< int >::iterator, or map< string, list< string >>::const_iterator comes in handy. The auto type inference helps us write less verbose code.

In addition to auto, the C++0x standard introduces a new keyword, called decltype (think of it as ‘typeof’), that can be used to determine the type of an expression at compile time.

However, this new keyword was not yet introduced in Visual Studio 2010 CTP. According to Stephan T. Lavavej from the VC++ team, it might be possible to be introduced in a next CTP or beta version.

Implementing auto doesn’t implement decltype (C++0x’s name for what was previously called typeof) for free.

Paraphrasing our libraries and compiler front-end program manager Damien Watkins, the CTP is only the first look at our VC10 functionality and there is definitely more to come. We understand that certain features “go together”, and that adding complementary features is a good thing in general. As always, customer feedback is a vital resource in forming our plans.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.