Skip to content
C++

Type Deduction

auto, decltype, template deduction.

By EZ4Code Team
autotype-inference

Code

#include <iostream>
#include <vector>
#include <string>
#include <type_traits>

int main() {
    // auto
    auto x = 42;          // int
    auto y = 3.14;        // double
    auto s = "hello"s;    // std::string
    auto& ref = x;        // int&
    auto* ptr = &x;       // int*

    // auto and containers
    std::vector<int> v = {1, 2, 3};
    for (auto it = v.begin(); it != v.end(); ++it) {
        std::cout << *it << " ";
    }

    // decltype
    int a = 10;
    decltype(a) b = 20;   // int
    decltype(auto) c = a; // int

    // trailing return type
    auto add = [](auto a, auto b) -> decltype(a + b) {
        return a + b;
    };

    // structured bindings (C++17)
    std::pair p = {1, "hello"};
    auto [num, str] = p;
    std::cout << num << " " << str << "\n";

    // if constexpr (C++17)
    auto process = [](auto value) {
        if constexpr (std::is_integral_v<decltype(value)>) {
            std::cout << "integer: " << value << "\n";
        } else {
            std::cout << "other: " << value << "\n";
        }
    };
    process(42);
    process(3.14);

    // decltype checks type
    static_assert(std::is_same_v<decltype(x), int>);
    return 0;
}

Explanation

auto deduces types; decltype gets expression types; structured bindings destructure and bind.

More C++ Snippets