decltype


Keyword: decltype

decltype is a keyword in C++ that is used to query the type of an expression at compile time. It allows you to deduce the type of a variable or an expression without explicitly specifying the type. This is particularly useful when working with templates or when you want to avoid redundant type declarations.

Example 1: Basic Usage

#include <iostream>

int main() {
    int x = 5;
    double y = 3.14;

    // Use decltype to get the type of x
    decltype(x) a; // a is of type int
    a = 10;

    // Use decltype to get the type of y
    decltype(y) b = y * 2; // b is of type double

    std::cout << "a: " << a << std::endl;
    std::cout << "b: " << b << std::endl;

    return 0;
}

Explanation

Example 2: Usage with Functions

Use with function return types

#include <iostream>

int add(int a, int b) {
    return a + b;
}

int main() {
    int x = 10;
    int y = 20;

    decltype(add(x, y)) result; // result is of type int
    result = add(x, y);

    std::cout << "result: " << result << std::endl;

    return 0;
}

Example 3: Usage with template functions

#include <iostream>

template<typename T1, typename T2>
auto add(T1 a, T2 b) -> decltype(a + b) {
    return a + b;
}

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

    auto result = add(x, y); // result is of type double

    std::cout << "result: " << result << std::endl;

    return 0;
}

Explanation

In the template function add, decltype(a + b) is used to deduce the return type based on the types of a and b. In this case, since one of the operands is double, the result is double.

Example 4: Usage with template functions

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3};

    // Capture the type of the first element in the vector
    decltype(vec[0]) first_element = vec[0];
    first_element = 10;

    std::cout << "first_element: " << first_element << std::endl;

    return 0;
}

Explanation

decltype(vec[0]) deduces the type of the first element of the vector, which is int& (a reference to int). This allows you to create variables with the exact type of the elements in a container.

Summary

Previous Page | Course Schedule | Course Content