[英]Passing array to function in C++
Why does the following not compile 为什么以下内容无法编译
#include <iostream>
template <typename T, size_t N>
const size_t len(T[N]){
return N;
}
int main(int argc, char* argv[]) {
using namespace std;
int arr[] = {1, 2, 3};
cout << len(arr);
}
but this does: 但是这样做:
#include <iostream>
const size_t foo(int[3]) {
return 42;
}
int main(int argc, char* argv[]) {
using namespace std;
int arr[1] = {123};
cout << foo(arr);
}
but with obviously incorrect argument and strangely only with the parameter identifier omitted 但参数显然不正确,并且奇怪的是仅省略了参数标识符
I am using GCC 4.9.2 with -std=c++1y 我正在将GCC 4.9.2与-std = c ++ 1y一起使用
edit: 编辑:
the error message for the first example: 第一个示例的错误消息:
main.cpp:12:24: error: no matching function for call to 'len(int [3])'
cout << len(arr);
^
main.cpp:12:24: note: candidate is:
main.cpp:4:18: note: template<class T, unsigned int N> const size_t len(T*)
const size_t len(T[N]){
^
main.cpp:4:18: note: template argument deduction/substitution failed:
main.cpp:12:24: note: couldn't deduce template parameter 'N'
cout << len(arr);
^
A function argument that looks like an array is actually a pointer, for bizarre historical reasons. 出于奇怪的历史原因,看起来像数组的函数参数实际上是指针。 If you specify an array size, then it's ignored.
如果指定数组大小,则将忽略它。 So the template is equivalent to
所以模板相当于
template <typename T, size_t N>
const size_t len(T*){
return N;
}
The argument can be pointer or anything convertible to one, including an array of any size, so N
cannot be deduced from the argument. 参数可以是指针,也可以是任何可转换为参数的值,包括任何大小的数组,因此无法从参数中推导出
N
You can fix this by taking the array by reference: 您可以通过引用引用来解决此问题:
template <typename T, size_t N>
size_t len(T(&)[N]){
return N;
}
Now the argument can only be an array of known size, and N
will be deduced from that size. 现在,参数只能是已知大小的数组,并且将从该大小中推导出
N
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.