...

/

The decltype Specifier

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:

int f() { return 42; }
int g() { return 0; }
int g(int a) { return a; }
struct wrapper
{
int val;
int get() const { return val; }
};
int a = 42;
int& ra = a;
const double d = 42.99;
long arr[10];
long l = 0;
char* p = nullptr;
char c = 'x';
wrapper w1{ 1 };
wrapper* w2 = new wrapper{ 2 };
Defining variables and functions to use with decltype specifier

The following listing shows multiple uses of the decltype specifier. The rule that applies in each case, as well as the deduced type, is specified on each line in a ...