Oracle Blog

Wednesday May 09, 2012

Decltype was among the first C++11 features implemented in GCC. It has roots in a very old GNU extension named __typeof__, also usable in C and well known to users of the GNU Compiler Collection. The C++11 conforming implementation of the idea landed in GCC 4.3.x in 2008. It overcame some defects of __typeof__. Both decltype and __decltype are available in GCC; the former only in c++11 mode, the latter both in c++11 and c++98 mode. The legacy __typeof__ is now unmaintained, meaning no problematic aspects with it will be addressed in future, besides of course making sure that what used to work keeps on working.

That said, let's introduce the basic concept of decltype. In its essence it's quite simple: the decltype operator queries the type of an expression. When this is integrated with other C++11 features it can enable rather interesting programming constructs.

A range of basic examples (from the ISO Document N2343. See some of the references therein for
historical background and rationale) follows:

As shown by these, decltype is not affected by the limitations of the traditional __typeof__ with respect to reference types. See cases (1) and (4), which show that such types are handled in a consistent way. It is, as such, fully integrated into the modern C++11 type system.

Decltype turns out to be very useful with templates in the context of generic programming, when the same generic function or class can be instantiated for different types. Via decltype the code can easily query the type of generic expressions, for example: