c++ - int a[5]和int(&a)[5]在模板参数推导上的区别

标签 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;
}

运行时打印预期结果:

2 3 4 5 6
3 4 5 6 7

但是,当我试图让我的编译器 (VS 2010) 推断出 5 时,它无法从“int [5]”推断出“int [n]”的模板参数

一些研究导致了更新的 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_a还是调用arrfun_b,程序的结果都是一样的。

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

最佳答案

编译器默默地将函数参数的类型 int a[N] 更改为 int *a 并因此丢失了数组的大小。 int(&a)[5] 是对大小为 5 的数组的真正引用,不能传递任何其他大小的数组。

关于c++ - int a[5]和int(&a)[5]在模板参数推导上的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10505259/

相关文章:

c++ - Z3:如何在不使用硬编码索引的情况下从model()访问变量?

android - OpenGL 3.0 ES 中的错误纹理渲染

php - 使用短代码从数据库中检索数据

javascript - 独特的数组。扫雷 JavaScript

javascript - Meteor template.find 未定义

c++ - 模板函数特化 : linker error

c++ - 我可以从智能卡中的 key 容器中获取公钥/私钥对吗?

algorithm - 从大表中消除 "bad"项目的多维过滤器?

javascript - 模板不触发事件的主干 View

c++ - 获取 QGraphicsView 的可见矩形?