Home >Backend Development >C++ >How Does Template Argument Deduction Determine Array Sizes in C ?

How Does Template Argument Deduction Determine Array Sizes in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 12:12:14920browse

How Does Template Argument Deduction Determine Array Sizes in C  ?

How Template Argument Deduction Uncovers Array Sizes

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.

Template Argument Deduction

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:

  • For the a array (length 6): The compiler deduces T as int and N as 6. It generates a specialized function:
void cal_size_int_6(int (&a)[6]) {
  std::cout << "size of array is: " << 6 << std::endl;
}
  • For the b array (length 1): Again, the compiler infers T as int and N as 1, producing another specialized function:
void cal_size_int_1(int (&a)[1]) {
  std::cout << "size of array is: " << 1 << std::endl;
}

Separate Function Calls

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn