The decltype Specifier

Explore the concept of the decltype specifier and its implementation in C++ programming.

The decltype specifier, introduced in C++11, returns the type of an expression. It’s usually used in templates together with the auto specifier. Together, they can be used to declare the return type of a function template that depends on its template arguments or the return type of a function that wraps another function and returns the result from executing the wrapped function.

The rules of the decltype specifier

The decltype specifier is not restricted for use in template code. It can be used with different expressions, and it yields different results based on the expression. The rules are as follows:

  • If the expression is an identifier or a class member access, then the result is the type of the entity that is named by the expression. If the entity doesn’t exist or it’s a function that has an overload set (more than one function with the same name exists), then the compiler will generate an error.

  • If the expression is a function call or an overloaded operator function, then the result is the return type of the function. If the overloaded operator is wrapped in parentheses, these are ignored.

  • If the expression is an lvalue, then the result type is an lvalue reference to the type of expression.

  • If the expression is something else, then the result type is the type of the expression.

To understand these rules better, we’ll look at a set of examples. For these, we’ll consider the following functions and variables that we’ll use in decltype expressions:

Get hands-on with 1200+ tech skills courses.