Understanding Template Argument Deduction in Function Templates
Consider the following code where a function template cal_size is used to calculate and print the size of arrays:
#include <iostream> template <typename T, size_t N> void cal_size(T (&a)[N]) { std::cout << "size of array is: " << N << std::endl; }
When the program executes, it prints the correct size for both arrays:
int a[] = {1,2,3,4,5,6}; int b[] = {1}; cal_size(a); cal_size(b);
So, how does the template function cal_size automatically deduce the size of the passed arrays, even though the size is not explicitly passed as an argument?
The answer lies in the concept of template argument deduction in C . Here's how it works:
During compilation, the compiler performs template argument deduction to determine the type of T and the value of N based on the actual type of the argument passed to the template function. In this case, when cal_size is called with the argument a, the compiler deduces T as int and N as 6, creating a specialized function cal_size_int_6 at compile time:
void cal_size_int_6(int (&a)[6]) { std::cout << "size of array is: " << 6 << std::endl; }
Similarly, for the argument b, the compiler deduces T as int and N as 1, resulting in the specialization cal_size_int_1:
void cal_size_int_1(int (&a)[1]) { std::cout << "size of array is: " << 1 << std::endl; }
Therefore, the original cal_size template effectively creates two separate function specializations, each with its own hardcoded T and N values. This process ensures that the correct array size is printed for each call to cal_size.
The above is the detailed content of How Does C Template Argument Deduction Determine Array Sizes in Function Templates?. For more information, please follow other related articles on the PHP Chinese website!