Sometimes you need to declare a type to be the same as something else.

You can use decltype just like auto. When you want to declare a local variable and initialize it right away, then auto really is the better choice. But maybe you want to declare a class member variable and your code won’t get around to initializing it with a value until the constructor or some other member method runs. You can’t use auto in this situation because the compiler doesn’t have anything to initialize the value with. As long as you have the other type available, which you should, then that’s all you need for decltype. This will give you the benefits of declaring a data member type based on some other type that could change as you write your application. And you don’t need to worry about initializing it right away. It will still have a specific type.

It also has an added benefit of following the declared type of the expression you pass to decltype exactly. Unlike auto which strips off reference or const qualifiers, the decltype operator will leave those intact.

This is actually one case where you might have to use decltype instead of auto even if you are declaring a local method variable and have an initializer handy. I explained in episode 137 how you can force an auto declaration to be const or to be a reference. But what if you don’t want to force it? What if you want your local variable to be a reference if you’re using a reference type to initialize it and you want it to have its own copy if you’re initializing it with a non-reference? The auto declaration by itself will always give you a new copy of the variable. And an auto reference will always give you a reference. If instead, you want something that can more closely follow the actual declared type of the thing being used to initialize your variable, then use decltype.

There are other uses of decltype too. You’ll find this operator very useful for all those places where you want some type to follow the type of some expression or other type but aren’t interested in using that type right away as an initializer.