Use Template Argument Deduction for Simplicity and Clarity
Explore how C++20 enhances template argument deduction to make your code simpler and clearer. Understand how the compiler infers template types for functions and classes without explicit specification, reducing errors and improving readability. This lesson covers function templates, class templates, parameter packs, and deduction guides to boost your coding efficiency.
We'll cover the following...
Template argument deduction occurs when the types of the arguments to a template function, or class template constructor (beginning with C++17), are clear enough to be understood by the compiler without the use of template arguments. There are certain rules to this feature, but it's mostly intuitive.
How to do it
In general, template argument deduction happens automatically when we use a template with clearly compatible arguments. Let's consider some examples.
In a function template, argument deduction usually looks something like this:
template<typename T>const char * f(const T a) {return typeid(T).name();}int main() {cout << format("T is {}\n", f(47));cout << format("T is {}\n", f(47L));cout << format("T is {}\n", f(47.0));cout << format("T is {}\n", f("47"));cout << format("T is {}\n", f("47"s));}
Output:
T is intT is longT is doubleT is char const *T is class std::basic_string<char...
Because the types are easily discernable there is no reason to specify a template parameter like f<int>(47) in the function call. The compiler can deduce the <int> ...