From 2b2ebe64b357a6bd2f01531bb4bde0731018eb50 Mon Sep 17 00:00:00 2001 From: Anthony Calandra Date: Mon, 27 Feb 2023 21:41:12 -0500 Subject: [PATCH] Add CTAD. --- CPP17.md | 34 ++++++++++++++++++++++++++++++++++ README.md | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/CPP17.md b/CPP17.md index 26646c8..f26c059 100644 --- a/CPP17.md +++ b/CPP17.md @@ -19,6 +19,7 @@ C++17 includes the following new language features: - [direct-list-initialization of enums](#direct-list-initialization-of-enums) - [\[\[fallthrough\]\], \[\[nodiscard\]\], \[\[maybe_unused\]\] attributes](#fallthrough-nodiscard-maybe_unused-attributes) - [\_\_has\_include](#\_\_has\_include) +- [class template argument deduction](#class-template-argument-deduction) C++17 includes the following new library features: - [std::variant](#stdvariant) @@ -360,6 +361,39 @@ It can also be used to include headers existing under different names or locatio #endif ``` +### Class template argument deduction +*Class template argument deduction* (CTAD) allows the compiler to deduce template arguments from constructor arguments. +```c++ +std::vector v{ 1, 2, 3 }; // deduces std::vector + +std::mutex mtx; +auto lck = std::lock_guard{ mtx }; // deduces to std::lock_guard + +auto p = new std::pair{ 1.0, 2.0 }; // deduces to std::pair +``` + +For user-defined types, *deduction guides* can be used to guide the compiler how to deduce template arguments if applicable: +```c++ +template +struct container { + container(T t) {} + + template + container(Iter beg, Iter end); +}; + +// deduction guide +template