Class template argument deduction (CTAD) lets C++17 infer a class template’s arguments from construction arguments, reducing repeated type spelling. For example, std::vector data{ 1 } deduces a vector of integers. section 2.1
Use CTAD when the construction arguments provide enough information:
- Write std::vector data{ 1 } instead of spelling std::vector<int>. section 2.1
- Write std::pair two_words{"Hello,"s, "world!"s}; to deduce a pair of strings. section 7.1.2
- Write std::tuple three_numbers{ 1, 1.23, 4.5f }; to deduce int, double, and float elements. section 7.1.2
- Do not expect auto data = std::vector{} to work: an empty vector supplies no element type to deduce. section 2.1
A small container experiment
Start with std::vector<int> data{ 1 } and display its first value. Then replace the declaration with std::vector data{ 1 }; the behavior stays the same while CTAD removes the explicit element type. Compile, modify the initializer, and observe which types can be inferred. section 2.1
Listing 2.1 Filling and displaying a container
#include <iostream> #1
#include <vector> #1
void generate_triangle()
{
std::vector<int> data{ 1 }; #2
for (auto number : data) #3
{
std::cout << number << ' ';
}
std::cout << '\n';
}
int main()
{
generate_triangle();
}
The complete vector example shows the explicit form that CTAD can shorten, alongside initialization and range-based iteration. section 2.1
