user3425082
user3425082

Reputation: 139

Be confused with argument in c++ function?

What is the difference between 2 fucntions?

//a

template <typename T, int N>
int g( T (&a)[ N ] )
{
    return N;
}

//b    

template <typename T, int N>
int g( T &a[ N ] )
{
    return N;
}

It is ok to compile the code //a, but for //b I get an error: "declaration of 'a' as array of references". Can anyone explain this error more clearly to me? Thanks!

Upvotes: 2

Views: 76

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

In C++, the syntax for some types are weird because of which such confusion often arises.

  • T (&a)[N] is a reference to an array of T of size N, which is allowed by the language, hence the first code compiles.

  • T &a[N] is an array of references (to T) of size N which is NOT allowed by the language, hence it doesn't compile.

Upvotes: 5

Tony
Tony

Reputation: 246

In the second case, operator precedence means that the indexing [] comes before the reference &. In the first case, you are making a reference to an array with N objects of type T, whereas in the second case, you have an array with N references to objects of type T, which is not valid.

Upvotes: 2

Related Questions