一个[5]和INT INT之间的差(&放大器;一个)[5]在模板参数扣除 [英] The difference between int a[5] and int (&a)[5] in template parameter deduction

查看:125
本文介绍了一个[5]和INT INT之间的差(&放大器;一个)[5]在模板参数扣除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This question is about functions that take arrays of statically known size.

就拿以下最低的程序:

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

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

Which, when run, prints the expected result:

2 3 4 5 6
3 4 5 6 7

然而,当我试图让我的编译器(VS 2010)演绎 5 ,它不能推导出模板参数的'廉政[N ]'从'廉政[5]

研究有点导致更新 arrfun_b ,其中模板参数推导如下:

A bit of research resulted in the updated arrfun_b where the template parameter deduction works:

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_a arrfun_b 被调用。

到目前为止,我已经找到了唯一的区别就是模板参数推导是否正常工作,如果它是可调用的N不是5的功能...

So far, the only difference I have found is whether the template argument deduction works and if it is possible to call the function with an N that is not 5...

推荐答案

,编译器默默地改变函数参数类型 int类型的[N] 为int * A ,从而失去了数组的大小。 INT(安培;一)[5] 是真正的大小5数组的参考,并不能传递任何其他大小的数组。

The compiler silently changes the type of function argument int a[N] to int *a and thus loses the size of the array. int(&a)[5] is truly a reference to an array of size 5, and cannot be passed an array of any other size.

这篇关于一个[5]和INT INT之间的差(&放大器;一个)[5]在模板参数扣除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆