-->

一个[5]和INT INT之间的差(&一)[5]在模板参数扣(The difference betw

2019-07-29 07:46发布

这个问题是关于采取静态已知大小的数组功能。

举个例子以下最低的程序:

#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;
}

其中,在运行时,打印预期的结果:

2 3 4 5 6
3 4 5 6 7

然而,当我试图让我的编译器(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;
}

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

到目前为止,我已经找到了唯一的区别就是模板参数推导是否可行,是否有可能以N不是5调用函数...

Answer 1:

编译器默默改变功能参数的类型int a[N]int *a并因此失去阵列的大小。 int(&a)[5]是真正到大小为5的数组的引用,而不能传递任何其他尺寸的阵列。



Answer 2:

我认为它的引用和指针之间的差值。

arrfun_a将指针传递到int。

arrfun_b传递到整数数组的引用。



文章来源: The difference between int a[5] and int (&a)[5] in template parameter deduction