Skip to content


The keyword “auto”

October 18, 2011

There are several uses for the keyword auto, some obvious, others a little more obscure, let’s start with the obvious.

If you put auto in front of the name of a variable, then the compiler deduces the type of that variable. Naturally, it must be assigned to the result of an expression immediately:

auto i = 42;
std::vector<std::pair<int, std::string>> array;
auto iter = array.begin();

So now you don’t have to type out all of those long types anymore.

We can do better than that, we can combine auto with the range-for loop. Suppose that we have a vector of some class that is expensive to copy, and we want to iterate over everything in it. We want to use auto, but we want to guarantee that we get a reference, not a copy. Furthermore, we want a const reference. Here is how we do that:

for (const auto& element : myarray) 
  //do stuff that reads from element

In case you’re tempted to liberally throw around auto‘s, don’t. They can’t be used for function arguments (that doesn’t make sense, that’s what templates are for), including lambda functions. Unfortunately the standard doesn’t allow a lambda function’s arguments to be templated, so you’ll have to stick with declaring the full type of arguments there.

Finally, we can use auto in a rather sneaky way to determine the return type of a function. When the return type of a function depends on template arguments, we no longer have to do some crazy metaprogramming thing to determine the return type. We can simply use decltype. For example:

template <typename T>
bar() {
  //do some stuff here which returns a Foo&lt;T&gt;

However, this doesn’t work if the argument to decltype depends on the arguments to the function, instead we can use auto and -> to put the return type after the function arguments:

template <typename T, typename U>
foo(T t, U u)
  -> decltype(t(u))
  return t(u);

From → Language

Leave a Comment

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: