Turn from:
http://blog.csdn.net/hongjiqin/article/details/5739935
In C + +, if you want to pass an array to a function, you typically pass in two arguments, an array pointer, and an array size
Cases:
void print_1 (int n, int *datas)
{
for (int i = 0; i < n; ++i)
{
Std::cout << Datas[i] << "";
}
Std::cout << Std::endl;
}
For this function, we can use it this way:
const int N = 3;
int Datas[n] = {1, 2, 3};
Print_1 (N, datas);
But for this function, we may be wrong about the size of n, which can go awry at run time, such as using:
const int N = 3;
int Datas[n] = {1, 2, 3};
Print_1 (4, datas);
Sometimes we want a function to accept only an array of the specified size, for example, we want to accept only an array of size 3:
void print_2 (int datas[3])
{
for (int i = 0; i < 3; ++i)
{
Std::cout << Datas[i] << "";
}
Std::cout << Std::endl;
}
In practice, however, the above function does not work correctly:
const int N = 3;
int Datas[n] = {1, 2, 3};
Print_2 (datas);
int datas2[n-1] = {1, 2};
Print_2 (DATAS2);
That is, we passed in an array of size 2, the compiler didn't report any errors, and 3 of our function interface print_2 (int datas[3]) didn't do any of the work.
In fact, the above function interface should write this:
void Print_3 (int (&datas) [3])
{
for (int i = 0; i < 3; ++i)
{
Std::cout << Datas[i] << "";
}
Std::cout << Std::endl;
}
At this point, we are right if we use this
const int N = 3;
int Datas[n] = {1, 2, 3};
Print_3 (datas);
And if we use this, the compiler will complain.
int datas2[n-1] = {1, 2};
Print_3 (DATAS2);
Based on the above example (print_3), we can use templates for generic implementations
Template
void Print_4 (int (&datas) [N])
{
for (int i = 0; i < N; ++i)
{
Std::cout << Datas[i] << "";
}
Std::cout << Std::endl;
}
At this point, we can pass an array of any size without worrying about passing the wrong arguments to the function.
const int N = 3;
int Datas[n] = {1, 2, 3};
Print_4 (datas);
int datas2[n-1] = {1, 2};
Print_4 (DATAS2);
If we pass the error parameter, the function will complain
const int N = 3;
int Datas[n] = {1, 2, 3};
Print_4<4 > (datas);