How does C++17 class template argument deduction turn Field f("id") into Field<std::string>, and what does a deduction guide add?
answer
- constructors become deduction candidates
- string literal deduces const char* first
- guide maps argument types to arguments
- braces prefer initializer_list
basics
~20 sSince C++17 the compiler deduces a class template's arguments from the initializer by treating each constructor as a function template. A deduction guide adds its own rule, such as Field(const char*) -> Fieldstd::string, which beats the constructor's result.
solid answer
~50 sClass template argument deduction (CTAD, C++17) lets you write `Field f("id")` without `<...>`. The compiler forms a set of imaginary function templates: one per constructor of the primary template, whose return type is the class with its template parameters, plus one per **user-defined deduction guide**. It runs overload resolution on the initializer against that set, and the winner's return type is the deduced class. With only `explicit Field(T v)`, the literal deduces `T = const char*`. The guide `Field(const char*) -> Field<std::string>;` matches equally well, and overload resolution's tie-breakers prefer it — it is a non-template, and it comes from a guide — so `f` is `Field<std::string>`. Guides matter when constructor parameters do not mention `T` directly — the standard containers' iterator-pair guides are the classic case. CTAD is all-or-nothing (`std::pair<int> p(1, 2.0)` is an error), and braces prefer `std::initializer_list`, so `std::vector v{it1, it2}` holds two iterators.
code
cpp · 24 lines#include <cstdio>
#include <string>
#include <type_traits>
#include <vector>
template <class T> struct Field {
T value;
explicit Field(T v) : value(v) {}
};
Field(const char*) -> Field<std::string>; // deduction guide
int main() {
Field a(42); // Field<int>, from the constructor
Field b("id"); // Field<std::string>, from the guide
static_assert(std::is_same_v<decltype(a), Field<int>>);
static_assert(std::is_same_v<decltype(b), Field<std::string>>);
std::vector<int> src{1, 2, 3};
std::vector copy{src}; // copy deduction: vector<int>
std::vector range(src.begin(), src.end()); // iterator guide: vector<int>
std::vector oops{src.begin(), src.end()}; // braces: two iterators
static_assert(std::is_same_v<decltype(oops), std::vector<std::vector<int>::iterator>>);
std::printf("%zu %zu %zu %s\n", copy.size(), range.size(), oops.size(), b.value.c_str());
}go deeper
Know that since C++17 you can write std::pair p(1, 2.0) or std::vector v{1, 2, 3} and the compiler fills in the template arguments from the initializer.
Explain the candidate set: one function template per constructor, the copy candidate and user guides, resolved by ordinary overload resolution, and show why the string-literal guide is needed.
Predict the brace-versus-parenthesis trap, the copy-deduction result and the all-or-nothing rule, and know which C++20 additions, such as aggregate deduction, a codebase's standard enables.
Decide where CTAD helps readability and where a spelled-out type documents intent, especially for types whose deduced argument is not obvious from the initializer.
## What CTAD is **Class template argument deduction (CTAD)**, added in C++17, deduces the template arguments of a class template from the initializer of a variable whose type names the template without arguments. `std::pair p(1, 2.0)` becomes `std::pair<int, double>`; `std::vector v{1, 2, 3}` becomes `std::vector<int>`. Before C++17 the same effect needed a helper such as `std::make_pair`, because only function templates deduced their arguments. ## How the compiler does it The compiler builds a set of **notional function templates** and performs ordinary overload resolution on the initializer: 1. For each constructor of the primary class template, a function template with the class's template parameters plus the constructor's own, taking the constructor's parameters and returning the class specialization. 2. A **copy deduction candidate**: `template<class T> Field(Field<T>) -> Field<T>`, which is why `std::vector copy{src}` copies a `std::vector<int>` instead of wrapping it. 3. Since C++20, an **aggregate deduction candidate** for an aggregate that has no deduction guides, built from the member types. 4. Each **user-defined deduction guide** in scope. The selected candidate's return type is the deduced type, and the variable is then initialized normally. If a guide and a constructor-derived candidate are otherwise equally good, a tie-breaker prefers the one generated from the guide. ## The Field example ```cpp template <class T> struct Field { T value; explicit Field(T v) : value(v) {} }; Field(const char*) -> Field<std::string>; ``` - `Field a(42)`: only the constructor candidate matches; `T = int`. - `Field b("id")`: the constructor candidate deduces `T = const char*` after array-to-pointer decay. The guide takes `const char*` exactly as well, and it is preferred — it is a non-template function, and it comes from a guide — so `b` is `Field<std::string>`. Without the guide, `b` would store a pointer to the literal — usually not what a serialization field wants. A guide is written at the same scope as the template, has the form `TemplateName(params) -> TemplateName<args>;`, may itself be a template, and may be marked `explicit`, in which case copy-initialization such as `Field f = "id";` does not use it. ## When guides are essential Constructors whose parameters do not name the template parameter directly deduce nothing. The standard containers' iterator-pair constructor is the textbook case: `vector(InputIt first, InputIt last)` has no `T` in it, so `<vector>` ships a guide that maps an iterator pair to `vector<iter_value_t<InputIt>>`. That is why `std::vector range(src.begin(), src.end())` deduces `std::vector<int>`. ## Writing a guide for an iterator constructor The same pattern serves your own types. A `Column<T>` constructed from an iterator pair deduces nothing from the constructor, because `T` does not appear in it, so you add a guide that reads the element type from the iterator: ```cpp template <class T> struct Column { template <class It> Column(It first, It last); }; template <class It> Column(It, It) -> Column<typename std::iterator_traits<It>::value_type>; ``` Now `Column c(names.begin(), names.end());` deduces `Column<std::string>` when `names` holds strings. The guide is itself a template whose parameter is deduced from the arguments, and its return type computes the class's argument. ## Traps worth knowing | Code | Deduced type | Why | |---|---|---| | `std::vector v{src.begin(), src.end()}` | `vector<vector<int>::iterator>` | Braces prefer the `initializer_list` constructor | | `std::vector v(src.begin(), src.end())` | `vector<int>` | Parentheses reach the iterator-pair guide | | `std::vector copy{src}` | `vector<int>` | Copy deduction candidate beats wrapping | | `std::pair<int> p(1, 2.0)` | error | CTAD is all-or-nothing; a partial list is not deduced | | `Tagged t{2.5, 7}` (aggregate) | error in C++17, `Tagged<double>` in C++20 | Aggregate deduction arrived in C++20 | Other limits: - CTAD works in a variable declaration with an initializer, a `new` expression and a functional cast such as `std::pair(1, 2.0)`; a function parameter cannot use it. - A deduction guide never changes which constructor initializes the object; it only chooses the type. The guide `Field(const char*) -> Field<std::string>` works because `Field<std::string>` has a constructor taking `std::string`, which `"id"` converts to. - Deducing from a constructor can surprise readers. Some codebases restrict CTAD to vocabulary types such as `std::pair`, `std::lock_guard` and `std::array`, where the result is obvious. ## Why interviewers ask CTAD questions check whether a candidate can predict a type without a compiler: the copy candidate, the brace trap and the role of guides all produce types that look wrong until you know the mechanism.
- Why does Tagged t{2.5, 7} fail in C++17 for template<class T> struct Tagged { T value; int tag; }, and what changed?`Tagged` is an aggregate with no constructors, so in C++17 the only candidates are the notional default and copy candidates, and none takes two arguments; clang reports no viable constructor or deduction guide. C++20 added an aggregate deduction candidate built from the member types, so the same line deduces `Tagged<double>`. Before C++20 such types needed an explicit guide like `template<class T> Tagged(T, int) -> Tagged<T>;`.
- When would you mark a deduction guide explicit?An `explicit` guide behaves like an `explicit` constructor. Copy-initialization such as `F2 x = "id";` does not consider it, so for `template<class T> struct F2 { F2(T); }` that line deduces `F2<const char*>`, while `F2 y("id");` uses the guide and deduces `F2<std::string>`. If copy-list-initialization selects an explicit guide, the program is ill-formed. Mark a guide explicit when an `=`-style initialization should not silently pick the converted type.
- CTAD works with a partial list, so std::pair<int> p(1, 2.0) deduces the second type.
- A deduction guide chooses which constructor initializes the object.
- std::vector v{first, last} deduces the element type from the iterators.
- std::vector copy{src} creates a vector holding one vector.
- CTAD has worked for aggregates since C++17 without a guide.
Assumes C++17 for CTAD and deduction guides; aggregate deduction was added in C++20, so the Tagged aggregate example needs -std=c++20.