C++11 – Part 1: Automatic Types

My C++ skills are getting a bit rusty as I have not done much programming in that language lately. So I thought what better way to refresh my skills and learn new stuff than to go through the C++11 changes and write something about them. I will not cover all additions and changes to the standard, but instead focus on those I am likely to use, (which means they must be implemented in GCC). And even those I do focus on, will likely miss some subtleties that I find unimportant (or more likely am unaware of…). For those wanting actual detail, a late working paper that is a near final draft of the C++11 standard can be downloaded here.

This first post is going to focus on type deduction and its uses.

In C++98, you have to declare the type of every variable being used. C++11 introduces the auto keyword, which lets the compiler deduce the type of a variable given its initializer. So you could write:

auto x = 5;

and you would get that x is declared to be an int. Like everything in programming, there is times when you should use a feature and times when you should not… This is an example of a time where you should not. The use of auto should be reserved for situations where you really do not know the type of the result or that the type is unwieldy to write. For example:

template<class T, class U>
void dot_product(const vector<T> vt, const vector<U> vu)
  auto tmp = vt[i] * vu[i]

A bit of a contrived example, but it should be clear that the type of the result depends on the template parameters U and V so is unknown. I will get to the return type in the next post…

A more useful example where the type of the variable is known but unwieldy is:

std::vector<std::pair<std::string, int>> v;
for(auto i = v.begin(), i != v.end(), ++i) {

Here the type of i is known (std::vector<std::pair<std::string,int>>::const_iterator), but writing that would quickly become tedious and error prone. I guess most situations like this were previously handled with a typedef statement.

There are other uses of auto that will be covered in later posts when the relevant features are introduced.

The decltype operator takes an expression and returns it type. A trivial example:

int x = 5;
decltype(x) y = x;

This declares the variable y to have the same type as x. Of course you could use auto here (or preferably neither in this case…), but the use of decltype comes into its own when you actually need a type – for example, a return type, which will be covered in the second post in this series.

One thought on “C++11 – Part 1: Automatic Types

  1. Thanks for the concise and clear write-up! Looking forward to the rest in the series. Like many time-saving features, _auto_ is likely to be both a blessing and a curse, depending on how much it is over-used. Time will tell.