decltype specifier

From cppreference.com
 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Inspects the declared type of an entity or queries the return type of an expression.

Contents

[edit] Syntax

decltype ( entity ) (1) (since C++11)
decltype ( expression ) (2) (since C++11)

[edit] Explanation

1) If the argument is either the unparenthesised name of an object/function, or is a member access expression (object.member or pointer->member), then the decltype specifies the declared type of the entity specified by this expression.
2) If the argument is any other expression of type T, then
a) if the value category of expression is xvalue, then the decltype specifies T&&
b) if the value category of expression is lvalue, then the decltype specifies T&
c) otherwise, decltype specifies T

Note that if the name of an object is parenthesised, it becomes an lvalue expression, thus decltype(arg) and decltype((arg)) 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.

[edit] Keywords

decltype

[edit] Example

#include <iostream>
 
struct A {
   double x;
};
const A* a = new A();
 
decltype( a->x ) x3;       // type of x3 is double (declared type)
decltype((a->x)) x4 = x3;  // type of x4 is const double& (lvalue expression)
 
template <class T, class U>
auto add(T t, U u) -> decltype(t + u); // return type depends on template parameters
 
int main() 
{
    int i = 33;
    decltype(i) j = i*2;
 
    std::cout << "i = " << i << ", "
              << "j = " << j << '\n';
 
    auto f = [](int a, int b) -> int {
       return a*b;
    };
 
    decltype(f) f2{f}; // the type of a lambda function is unique and unnamed
    i = f(2, 2);
    j = f2(3, 3);
 
    std::cout << "i = " << i << ", "
              << "j = " << j << '\n';
}

Output:

i = 33, j = 66
i = 4, j = 9

[edit] See also

(C++11)
obtains the type of expression in unevaluated context
(function template)