An array does not fall into a pointer if it is passed by a const reference in a template function

This question comes from this:

C ++ pass an array to ask a question

but since the OP accepted the answer, I think no one will read it now.

I tried this code in g ++. It seems that the array does not break into a pointer when passing this function (the function returns the correct result):

#include <iostream> template <typename T> std::size_t size_of_array (T const & array) { return sizeof (array) / sizeof (*array); } int main () { int a [5]; std::cout << size_of_array (a) << '\n'; } 

Another user (sharptooth) said that he has the same behavior in VC ++ 10 with an attachment.

Can someone explain? Thanks.

+6
source share
2 answers

The decay of the array is not easy - it happens only when the program cannot be compiled without it. When you pass an array by reference, there is simply no need to decompose.

Note that a function template can also be written without dividing ugly sizeof expressions:

 template <typename T, std::size_t N> std::size_t size_of_array(T (&array)[N]) { return N; } 

When the client calls size_of_array , T and N automatically output by the template engine.

+12
source

You did not specify a function to accept a pointer, you wrote it to accept a reference to const, to accurately indicate the type of argument passed to it. Losing a pointer only happens if you are trying to assign a pointer to an array value.

+4
source

Source: https://habr.com/ru/post/895754/


All Articles