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

How Does C Template Argument Deduction Determine Array Sizes in Function Templates?

Mary-Kate Olsen
Release: 2024-11-30 15:22:12
Original
644 people have browsed it

How Does C   Template Argument Deduction Determine Array Sizes in Function Templates?

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 (&amp;a)[N])
{
    std::cout << "size of array is: " << N << std::endl;
}
Copy after login

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);
Copy after login

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 (&amp;a)[6])
{
    std::cout << "size of array is: " << 6 << std::endl;
}
Copy after login

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 (&amp;a)[1])
{
    std::cout << "size of array is: " << 1 << std::endl;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template