Automatic Type Deduction: decltype
Explore how decltype works in C++ to deduce the type of expressions and entities accurately. Understand the difference between its use for lvalues and rvalues, and see examples of decltype in templates and function pointers. This lesson builds your skills to effectively use automatic type deduction alongside auto in professional C++ programming.
We'll cover the following...
decltype vs auto
The decltype keyword was also introduced in C++11, though its functionality differs from auto. decltype is used to determine the type of an expression or entity.
Here is the correct format:
decltype(expression)
We can use auto to create variables, but decltype returns the type of an expression containing variables.
Rules
-
If the expression is an lvalue,
decltypewill return a reference to the data type of the expression -
If the expression is an rvalue,
decltypewill return the data type of the value
In line 7, the parentheses around i indicate that this is an expression instead of a variable. Hence, decltype computes int& instead of int.
decltype is not used as often as auto. It is useful with templates that can deduce the type of a function.
Here’s another example of decltype in action:
We can see how decltype deduces the types of different entities, including the function pointer in line 32.
In the next lesson, we’ll learn how to use decltype and auto together.