Home >Backend Development >C++ >How Does C Deduce Array Size in Function Templates?
In the provided C code, a function template named cal_size is declared to accept an array as its argument. The function template deduces the size of the array from the argument type and prints it.
The question arises: how does the template parameter N automatically get initialized to the correct size of the array without explicitly specifying it in the function call?
The key to understanding this behavior lies in the process of template argument deduction. When a template function is called, the compiler uses the actual type of the argument to deduce the values of the template parameters.
In the case of cal_size, the argument type is an array of elements of type T with a specified size N. The compiler deduces T from the element type of the array, and N from the size of the array.
When the argument a is passed to the function, the compiler deduces T as int and N as 6. Similarly, when b is passed, T is int and N is 1.
Based on the deduced values of T and N, the compiler generates separate, specialized versions of the function template. For each call, a specialized function is created with the specific type and size information of the argument array.
In this particular case, two specialized functions are generated:
The main function essentially translates to calling these specialized functions.
The above is the detailed content of How Does C Deduce Array Size in Function Templates?. For more information, please follow other related articles on the PHP Chinese website!