In c++, type of a reference to array is shown like int (&) [10]
. As an example, when I try to compile with g++ and clang the following code
template <typename T> void foo(T&);
int main() {
int a[] {1, 2, 3};
foo(a);
}
I get the following error:
undefined reference to `void foo<int [3]>(int (&) [3])'
In this error text, why is the type of argument shown as int (&) [3]
? Why don't we denote array reference types like references to integral types or class types, i.e. int [10] &
? What is the reason for using (&)
?
I know we can define a 'reference to array' variable like this:
int (&b)[3] = a;
And this definition indeed 'looks like' the type of b. But is this the only reason? Is there a problem related to the notation int [10] &
?
It comes from how the type of pointers to arrays look like: int(*)[10]
. The *
is just replaced by &
, like in all reference types.
The reason that pointers to arrays look like that is how it looks like in C, and C++ had no reason to change it.
int (*a)[10];
// "(*a)[10]" is an int
// The type of `a` is `int (*)[10]`, just remove the name
I don't see any technical reasons why int[10]*
and int[10]&
would not be possible as the name of the types for "pointer or reference to an array of 10 int
", other than compatibility with C