Here is the case of using std::swap to interchange values of two arrays.
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? Since a pointer of an int array doesn't have any information about its length.
A reference to array is only allowed to bind to an array of the correct extent. For example a int (&)[10]
cannot bind to an int
array of size other than 10, nor can it bind to an 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.