skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-type-deduction
This page is read only. You can view the source, but not change it.
# C++ type deduction **[Type deduction](https://en.cppreference.com/w/cpp/language/template_argument_deduction)** is the process where the compiler infers template argument types from function arguments or variable initializers. Different deduction rules apply to different contexts: plain parameters deduce without references, reference parameters preserve reference-ness, and `auto` deduction differs slightly from function template deduction. Understand type deduction to predict how templates behave and avoid surprises with reference stripping and decay. ## Example This example demonstrates type deduction rules for function templates and auto variables. ```cpp // compile: g++ -std=c++17 -o deduction deduction.cpp // run: ./deduction // description: type deduction rules for templates and auto #include <iostream> #include <type_info> template <typename T> void plain(T arg) { std::cout << "plain: " << typeid(T).name() << "\n"; } template <typename T> void ref(T& arg) { std::cout << "ref: " << typeid(T).name() << "\n"; } int main() { int x = 42; const int cx = 42; plain(x); // T = int plain(cx); // T = int (const stripped) ref(x); // T = int ref(cx); // T = const int (preserves const) auto a = x; // auto = int auto b = cx; // auto = int (const stripped) return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top