函数模板中的魔术参数 [英] Magic arguments in function templates
问题描述
在以下代码中
#include<iostream>
template<typename T,size_t N>
void cal_size(T (&a)[N])
{
std::cout<<"size of array is: "<<N<<std::endl;
}
int main()
{
int a[]={1,2,3,4,5,6};
int b[]={1};
cal_size(a);
cal_size(b);
}
正如预期的那样,两个数组的大小都被打印。但是如何N自动获得初始化为正确的数组大小的值(数组通过引用传递)?上述代码的工作原理是什么?
As expected the size of both the arrays gets printed. But how does N automatically gets initialized to the correct value of the array-size (arrays are being passed by reference)? How is the above code working?
推荐答案
初始化到任何东西。它不是变量。它不是一个对象。
N
是编译时常量。 N
仅在编译期间存在。 N
的值以及实际的 T
由称为模板参数扣除 em>。从传递给模板函数的参数的实际类型中推导出 T
和 N
。
N
does not get "initialized" to anything. It is not a variable. It is not an object. N
is a compile-time constant. N
only exists during compilation. The value of N
as well as the actual T
is determined by the process called template argument deduction. Both T
and N
are deduced from the actual type of the argument you pass to your template function.
在第一次调用中,参数类型为 int [6]
,因此编译器推断 T == int
和 N == 6
,生成一个单独的函数并调用它。让我们将它命名为 cal_size_int_6
In the first call the argument type is int[6]
, so the compiler deduces that T == int
and N == 6
, generates a separate function for that and calls it. Let's name it cal_size_int_6
void cal_size_int_6(int (&a)[6])
{
std::cout << "size of array is: " << 6 << std::endl;
}
注意,没有 T
并且在此函数中不再有 N
。
Note that there's no T
and no N
in this function anymore. Both were replaced by their actual deduced values at compile time.
在第一次调用中,参数类型为 int [1]
,因此编译器推导出 T == int
和 N == 1
以及调用它。让我们将它命名为 cal_size_int_1
In the first call the argument type is int[1]
, so the compiler deduces that T == int
and N == 1
, generates a separate function for that as well and calls it. Let's name it cal_size_int_1
void cal_size_int_1(int (&a)[1])
{
std::cout << "size of array is: " << 1 << std::endl;
}
您的主要
实质上可转换为
int main()
{
int a[]={1,2,3,4,5,6};
int b[]={1};
cal_size_int_6(a);
cal_size_int_1(b);
}
换句话说,您的 cal_size
模板生成两个不同的函数(即原始模板的特殊化),每个都有不同的值 N
(和 T
)硬编码到正文中。这就是模板在C ++中的工作原理。
In other words, your cal_size
template gives birth to two different functions (so called specializations of the original template), each with different values of N
(and T
) hardcoded into the body. That's how templates work in C++.
这篇关于函数模板中的魔术参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!