Template <class T>
Void func1 (T &, T &)
{
}
Template <class tt>
Void func2 (TT, TT)
{
}
Int main ()
{
Int A [10], B [10], C [20];
Func1 (a, B); // OK, array reference
Func1 (B, c); // error, when the parameter is referenced, the array cannot be converted to a pointer,
// B, C type (array length) does not match, refer to C ++ primer P538
Func2 (a, B); // OK, as an array pointer
Func2 (B, c); // OK, as an array pointer
Return 0;
}
1. You can define array references in C ++ to solve the "array price reduction" problem that cannot be solved in C. Let's first look at what "array price reduction" is. first look at the following:Code:
Void test (char array [20])
{
Cout <sizeof (array) <Endl; // output 4
}
Char array [20] = {0 };
Cout <sizeof (array) <Endl; // output 20 test (array );
We can see that for the same Array array, one output 4 and the other outputs 20. this is because the array in void test (char array [20]) is downgraded. Void test (char array [20]) is equivalent to void test (char array []). it is also equivalent to void test (char * const array). If you are interested, it is even equivalent to void test (char array [999]).
That is to say
Void test (char array [20])
{
Cout <sizeof (array) <Endl;
}
Reduced
Void test (char * const array)
{
Cout <sizeof (array) <Endl; // since it is char *, of course, output 4
}
In this case, the array size limit in the function declaration is invalid. The Void test (char array [20]) statement cannot guarantee that an array of 20 is received, that is, any char [] will be reduced to char *, which increasesProgramThe possibility of an error. To solve this problem, we can use the array reference of C ++ as the parameter. See the following code:
Void test (char (& array) [20]) // is it similar to char * P [20] and char (* P) [20?
{
Cout <sizeof (array) <Endl;
}
Char array [20] = {0 };
Cout <sizeof (array) <Endl;
Test (array );
In this way, the test function can only receive char [] with a size of 20, as shown in the following code:
Char array1 [10] = {0 };
Char array2 [20] = {0 };
Test (array1); // error: the real parameter is not a char [] with a size of 10.
Test (array2); // OK