这个模板魔术如何确定数组参数大小?

时间:2023-02-23
本文介绍了这个模板魔术如何确定数组参数大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在下面的代码中

#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 只在编译时存在.N 的值以及实际的 T 由称为模板参数推导的过程确定.TN 都是从传递给模板函数的参数的实际类型推导出来的.

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 == intN == 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; 
} 

请注意,此函数中不再有 TN.两者都在编译时被它们的实际推导值替换.

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 == intN == 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; 
} 

这里也是一样.

你的 main 基本上转化为

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模板产生了两个不同的功能(所谓的原始模板的specializations),每个都有不同的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++.

这篇关于这个模板魔术如何确定数组参数大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:模板推导中的偏序过程是什么 下一篇:使用继承的类模板避免公共成员不可见和源代码膨胀/重复的更好方法?

相关文章

最新文章