开发者

In regards to array size calculation [duplicate]

开发者 https://www.devze.com 2023-02-11 07:26 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Can someone explain this template code that gives me the size of an array?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Can someone explain this template code that gives me the size of an array?

Hi, I am looking at the answer posted here:

Computing length of array

Copied here:

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

Can some one pls explai开发者_JAVA技巧n me the significance of (&) ?


The & says the array is passed by reference. That prevents the type from decaying to pointer. Without passing by reference you would get that decay, and no information about the array size.

Non-template example:

void foo( int (&a)[5] )
{
    // whatever
}

int main()
{
    int x[5];
    int y[6];

    foo( x );           // ok
    //foo( y );         // !incompatible type
}

Cheers & hth.,


The & means that the array is to be passed by reference. Arrays can't be passed by value, because in this case they decay to a pointer to the first item. If that happens, the size information associated with the array type is lost.

It is in parenthesis, because otherwise that would mean the function accepts a pointer to reference. Although such a thing is not legal in C++, the syntax is consistent with how you declare a pointer to array.

int (*arr)[3]; // pointer to array of 3 ints
int* p_arr[3]; // array of pointers

int (&arr)[3]; // reference of array of 3 ints
int& r_arr[3]; //array of references (not legal in C++)
0

精彩评论

暂无评论...
验证码 换一张
取 消