C++ decltype Keyword

The decltype keyword in C++ is used to deduce the type of an expression at compile-time. Introduced in C++11, it allows you to determine the exact type of a variable, expression, or function result without explicitly knowing its type. This feature is particularly useful in template programming and when dealing with complex expressions or return types.


Syntax

</>
Copy
decltype(expression) variable_name;
decltype
The keyword used to deduce the type of the provided expression.
expression
An expression whose type is to be deduced, such as a variable, function, or operation.
variable_name
The name of the variable to be declared using the deduced type.

Examples

Example 1: Deducing Variable Type

This example demonstrates how to use decltype to deduce the type of a variable from another variable.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    int a = 10;
    decltype(a) b = 20; // 'b' has the same type as 'a'

    cout << "a: " << a << ", b: " << b << endl;
    return 0;
}

Output:

a: 10, b: 20

Explanation:

  1. The type of a is int.
  2. decltype(a) deduces the type of a and uses it to declare b.
  3. Both a and b are of type int, and their values are printed accordingly.

Example 2: Deducing Function Return Type

This example demonstrates using decltype to deduce the return type of a function.

</>
Copy
#include <iostream>
using namespace std;

int add(int x, int y) {
    return x + y;
}

int main() {
    decltype(add(0, 0)) result = add(5, 3); // Deduces the return type of 'add'
    cout << "Result: " << result << endl;
    return 0;
}

Output:

Result: 8

Explanation:

  1. The function add returns an int, which is deduced by decltype(add(0, 0)).
  2. The variable result is declared with the deduced type int.
  3. The result of the function call add(5, 3) is stored in result and printed.

Example 3: Using decltype with Expressions

This example demonstrates using decltype to deduce the type of an expression.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    int x = 10;
    float y = 5.5;

    decltype(x + y) z = x + y; // Deduces the type of the expression 'x + y'
    cout << "z: " << z << endl;
    return 0;
}

Output:

z: 15.5

Explanation:

  1. The expression x + y involves an int and a float, so the result is a float.
  2. decltype(x + y) deduces the type of the expression, which is float.
  3. The variable z is declared with type float and stores the result of x + y.

Key Points about decltype Keyword

  1. The decltype keyword deduces the type of an expression at compile-time.
  2. It is particularly useful in template programming and situations where the type is determined by complex expressions.
  3. decltype can deduce the type of variables, expressions, and function return values.
  4. Unlike auto, which deduces a type based on initialization, decltype queries the type of an expression without requiring initialization.