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_a或arrfun_b将被调用.
到目前为止,我发现的唯一区别是模板参数推导是否有效以及是否可以使用不是5的N来调用函数...
Mar*_*som 15
编译器默默改变功能参数的类型int a[N],以int *a及因而失去阵列的大小.int(&a)[5]确实是对大小为5的数组的引用,并且不能传递任何其他大小的数组.
| 归档时间: |
|
| 查看次数: |
648 次 |
| 最近记录: |