关于阵列大小计算

时间:2011-02-17 19:17:43

标签: c++

  

可能重复:
  Can someone explain this template code that gives me the size of an array?

嗨,我正在看这里发布的答案:

Computing length of array

在这里复制:

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

有人可以解释一下(&amp;)的重要性吗?

2 个答案:

答案 0 :(得分:7)

&表示数组是通过引用传递的。这可以防止类型衰减到指针。如果不通过引用传递,您将获得该衰减,并且没有关于数组大小的信息。

非模板示例:

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

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

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

干杯&amp;第h。,

答案 1 :(得分:2)

&amp;表示数组将通过引用传递。数组不能通过值传递,因为在这种情况下,它们会衰减为指向第一个项目的指针。如果发生这种情况,则与数组类型关联的大小信息将丢失。

它在括号中,否则意味着该函数接受指向引用的指针。虽然这样的事情在C ++中是不合法的,但语法与声明指向数组的指针一致。

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++)