简体   繁体   English

std swap如何推导数组的长度?

[英]How does std swap deduce the length of an array?

Here is the case of using std::swap to interchange values of two arrays. 这是使用std :: swap交换两个数组的值的情况。

int arr1[3]={1,2,3};
int arr2[3]={4,5,6};
std::swap(arr1,arr2);
//Then arr1 becomes {4,5,6} and arr2 becomes {1,2,3}

The swap function is declared as 交换函数声明为

template <class T, size_t N> void swap(T (&a)[N], T (&b)[N])
  noexcept (noexcept(swap(*a,*b)));

I am curious about the mechanisms of the size_t N deduction, how is it accomplished? 我对size_t N扣除的机制感到好奇,它是如何实现的? Since a pointer of an int array doesn't have any information about its length. 由于int数组的指针没有有关其长度的任何信息。

A reference to array is only allowed to bind to an array of the correct extent. 仅允许对array引用绑定到正确范围的数组。 For example a int (&)[10] cannot bind to an int array of size other than 10, nor can it bind to an int* . 例如,一个int (&)[10]不能绑定到大小不是10的int数组,也不能绑定到int* This is also true when you have a parameter of reference to array type. 当您有一个引用数组类型的参数时,也是如此。

When you pass an array to a function and the parameter is not a reference, the argument is decayed to a pointer to the array's first element. 当您将数组传递给函数并且参数不是引用时,参数将衰减为指向数组第一个元素的指针。 But when you pass an array by reference, for the purposes of template parameter deduction, the argument type is not decayed. 但是,当您通过引用传递数组时,出于模板参数推导的目的,参数类型不会衰减。 This is because a reference to array parameter can't bind to a pointer. 这是因为对数组参数的引用无法绑定到指针。 Since the argument type isn't decayed, the template parameter N can be correctly deduced. 由于参数类型没有衰减,因此可以正确推导模板参数N

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM