Home >Backend Development >C++ >How Does Template Argument Deduction Determine Array Sizes in C ?
In the provided C code, the template function cal_size prints the size of an array reference argument. It's intriguing how the template parameter N automatically reflects the length of the passed array.
N is not an initialized variable; it's a compile-time constant. Through a process known as template argument deduction, both T and N are inferred from the argument passed to the template function.
Consider the following calls to cal_size:
void cal_size_int_6(int (&a)[6]) { std::cout << "size of array is: " << 6 << std::endl; }
void cal_size_int_1(int (&a)[1]) { std::cout << "size of array is: " << 1 << std::endl; }
Essentially, the cal_size template translates to individual specialized functions with hardcoded values of N and T. The main function becomes equivalent to:
int main() { cal_size_int_6(a); cal_size_int_1(b); }
In summary, template argument deduction enables templates to deduce the array size from the argument type. The underlying mechanism involves generating specialized functions for each unique combination of argument types, each with its own statically determined N and T values.
The above is the detailed content of How Does Template Argument Deduction Determine Array Sizes in C ?. For more information, please follow other related articles on the PHP Chinese website!