C++ typeof vs decltype

GCC and compatible (Clang) compilers implement a feature known as typeof (or __typeof__).


This is a pre C++11 feature, omitted from the standard, and is unavailable Visual C++.

For the most part it does what you’d expect. Given a variable, it returns the type. This lets you create another instance of a type without having to use its full name. This is helpful if you happen to be using templates.

Regrettably, typeof seems to be somewhat flawed.

Generally speaking, there is no way using typeof to read type members (typedefs, structs, unions, classes).

As of C++11, a new keyword decltype was introduced. It is functionally the same as typeof, but the case shown above works. It has been available since GCC 4.3 (2008) and Visual C++ 2010.

In practice, you’re often using this in conjunction with an assignment. So if you have C++11 available, you may as well just use an auto.

*sigh*… I wish a certain company didn’t use GHS Multi, so I could … you know, use decltype and auto. 😉