The difference between int a [5] and int (& a) [5] when displaying template parameters

This question is about functions that accept arrays of statically known size.

Take, for example, the following minimum program:

#include <iostream> template<size_t N> void arrfun_a(int a[N]) { for(size_t i = 0; i < N; ++i) std::cout << a[i]++ << " "; } int main() { int a[] = { 1, 2, 3, 4, 5 }; arrfun_a<5>(a); std::cout << std::endl; arrfun_a<5>(a); return 0; } 

What at startup prints the expected result:

 2 3 4 5 6 3 4 5 6 7 

However, when I tried to get my compiler (VS 2010) to could not deduce template argument for 'int [n]' from 'int [5]' 5 , it could not deduce template argument for 'int [n]' from 'int [5]' .

Several studies led to the updated arrfun_b , where the deduction of the template parameter works:

 template<size_t n> void arrfun_b(int (&a)[n]) { for(size_t i = 0; i < n; ++i) std::cout << ++(a[i]) << std::endl; } 

The result of the program is the same whether arrfun_a or arrfun_b .

So far, the only difference I've found is whether the output of the template argument works, and if you can call a function with N that is not 5 ...

+8
c ++ arrays
source share
2 answers

The compiler silently changes the argument type of the function int a[N] to int *a and, therefore, loses the size of the array. int(&a)[5] really a reference to an array of size 5 and an array of any other size cannot be passed.

+14
source share

I think this is the difference between a link and a pointer.

arrfun_a passes a pointer to an int.

arrfun_b passes a reference to an array of integers.

+1
source share

All Articles