Function Template Argument Deduction
Develop a thorough understanding of function template argument deduction.
We'll cover the following...
We have briefly talked about the fact that the compiler can sometimes deduce the template arguments from the context of the function call, allowing us to avoid explicitly specifying them. The rules for template argument deduction are more complex, and we’ll explore this topic in this lesson.
Let’s start the discussion by looking at a simple example:
Note: The
iandsin the output above representintandshort, respectively.
In this snippet, process is a function template with a single type template parameter. The calls process(42) and process<int>(42) are identical because, in the first case, the compiler is able to deduce the type of the type template parameter T as int from the value of the argument passed to the function.
Rules for deducing template arguments
When the compiler tries to deduce the template arguments, it performs the matching of the types of the template parameters with the types of the arguments used to invoke the function. There are some rules that govern this matching. The compiler can match the following:
Types (both cv-qualified and nonqualified) of the form
T,T const, andT volatile:
Pointers (
T*), l-value references (T&), and r-value references (T&&):
Arrays such as
T[5], orC[5][n], whereCis a class type andnis a non-type template argument:
Pointers ...