Decltype Specifier
Decltype Specifier
Inspects the declared type of an entity or the type and value category of an expression.
Syntax
Explanation
1) If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, then decltype yields the type of the entity
named by this expression. If there is no such entity, or if the argument names a set of overloaded functions, the program is ill-formed.
If the argument is an unparenthesized id-expression naming a structured binding, then decltype yields the referenced type (described in the
(since C++17)
specification of the structured binding declaration).
If the argument is an unparenthesized id-expression naming a non-type template parameter, then decltype yields the type of the template
parameter (after performing any necessary type deduction if the template parameter is declared with a placeholder type). The type is non- (since C++20)
const even if the entity is a template parameter object (which is a const object).
2) If the argument is any other expression of type T, and
a) if the value category of expression is xvalue, then decltype yields T&& ;
b) if the value category of expression is lvalue, then decltype yields T& ;
c) if the value category of expression is prvalue, then decltype yields T .
If expression is a function call which returns a prvalue of class type or is a comma expression whose right operand is such a function call,
(until C++17)
a temporary object is not introduced for that prvalue.
If expression is a prvalue other than a (possibly parenthesized) immediate invocation (since C++20) , a temporary object is not materialized
(since C++17)
from that prvalue: such prvalue has no result object.
Because no temporary object is created, the type need not be complete or have an available destructor, and can be abstract. This rule doesn't apply to
sub-expressions: in decltype(f(g())) , g() must have a complete type, but f() need not.
Note that if the name of an object is parenthesized, it is treated as an ordinary lvalue expression, thus decltype(x) and decltype((x)) are often different
types.
decltype is useful when declaring types that are difficult or impossible to declare using standard notation, like lambda-related types or types that depend on
template parameters.
Notes
decltype
Example
#include <iostream>
#include <type_traits>
struct A { double x; };
const A* a;
// Alternatively:
auto getRefFwdGood1(const int* p) -> decltype(getRef(p)) { return getRef(p); }
static_assert(std::is_same_v<decltype(getRefFwdGood1), const int&(const int*)>,
"Returning decltype(return expression) also perfectly forwards the return type.");
int main()
{
int i = 33;
decltype(i) j = i * 2;
std::cout << "i and j are the same type? " << std::boolalpha
<< std::is_same_v<decltype(i), decltype(j)> << '\n';
Output:
See also