模板参数推导中int a [5]和int(&a)[5]之间的区别

gha*_*.st 9 c++ arrays templates template-argument-deduction

这个问题是关于采用静态已知大小的数组的函数.

以下面的最小程序为例:

#include <iostream>

template<size_t N>
void arrfun_a(int a[N])
{
    for(size_t i = 0; i < N; ++i)
        std::cout << a[i]++ << " ";
}

int main()
{
    int a[] = { 1, 2, 3, 4, 5 };
    arrfun_a<5>(a);
    std::cout << std::endl;
    arrfun_a<5>(a);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

运行时,打印预期结果:

2 3 4 5 6
3 4 5 6 7
Run Code Online (Sandbox Code Playgroud)

但是,当我试图让我的编译器(VS 2010)推断出5它时could not deduce template argument for 'int [n]' from 'int [5]'.

一些研究导致arrfun_b模板参数推导工作的更新:

template<size_t n>
void arrfun_b(int (&a)[n])
{
    for(size_t i = 0; i < n; ++i)
        std::cout << ++(a[i]) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

该方案的结果是一样的,无论是arrfun_aarrfun_b将被调用.

到目前为止,我发现的唯一区别是模板参数推导是否有效以及是否可以使用不是5的N来调用函数...

Mar*_*som 15

编译器默默改变功能参数的类型int a[N],以int *a及因而失去阵列的大小.int(&a)[5]确实是对大小为5的数组的引用,并且不能传递任何其他大小的数组.

  • 更重要的是,`int a [5]`在参数列表中成为`int*a`,其中`int(&a)[5]`对于5`int的数组真正是**引用** (5认同)
  • @dionadar:没有转换回数组.在arrfun_a里面,`a`的类型是指针. (3认同)