Is your 401k bleeding money by not offering low-cost index funds? Now there is a way to find out.
GreaterThanZero.com


C++ auto and decltype Explained

By Thomas Becker   about me  
 
Last updated: May 2013

Contents

  1. Introduction
  2. The auto Keyword: The Basics
  3. The auto Keyword: The Rest of the Story
  4. When auto Is Not a Luxury
  5. The decltype keyword: The Basics
  6. How decltype Deduces the Type of an Expression: Case 1
  7. How decltype Deduces the Type of an Expression: Case 2
  8. An Example to Put You on Guard
  9. Miscellaneous Properties of decltype
  10. New in C++14
  11. Summary and Epilogue
  12. Acknowledgments

Introduction

Most of the language features that were introduced with the C++11 Standard are easy to learn, and the benefit that they provide is quite obvious. Looking at them doesn't make you think, "Oh no, now I'm going to have to learn this." Instead, your immediate reaction is, "Oh great, I've always wanted that." In some cases, like lambdas, the syntax is a bit hairy, but that's of course not much of a problem. For me, the one big exception to all this were rvalue references. I had a really hard time wrapping my head around those. Therefore, I did what I always do when I need to understand something: I scraped up all the information I could get my hands on, then wrote an article on the subject. It turned out that a lot of people were having the same problem, and the article helped quite a few of them. Great, everybody's happy.

A while later, sometime in 2012, I noticed that there was another feature, or rather, a pair of features, in C++11 that I had not fully understood, namely, the auto and decltype keywords. With auto and decltype, unlike rvalue references, the problem is not that they are difficult to grasp. On the contrary, the problem is that the idea is deceptively easy, yet there are hidden subtleties that can trip you up.

Let's start with a good look at the auto keyword.