[英]How can a template function 'know' the size of the array given as template argument?
In the C++ code below, the templated Check function gives an output that is not what I would like: it's 1 instead of 3. I suspect that K is mapped to int*
, not to int[3]
(is that a type?). 在下面的C ++代码中,模板化的Check函数给出的输出不是我想要的:它是1而不是3.我怀疑K映射到
int*
,而不是int[3]
(是一个类型?) 。 I would like it to give me the same output than the second (non templated) function, to which I explicitly give the size of the array... 我希望它给出与第二个(非模板化)函数相同的输出,我明确给出了数组的大小...
Short of using macros, is there a way to write a Check function that accepts a single argument but still knows the size of the array? 如果没有使用宏,有没有办法编写一个接受单个参数但仍知道数组大小的Check函数?
#include <iostream>
using namespace std;
int data[] = {1,2,3};
template <class K>
void Check(K data) {
cout << "Deduced size: " << sizeof(data)/sizeof(int) << endl;
}
void Check(int*, int sizeofData) {
cout << "Correct size: " << sizeofData/sizeof(int) << endl;
}
int main() {
Check(data);
Check(data, sizeof(data));
}
Thanks. 谢谢。
PS: In the real code, the array is an array of structs that must be iterated upon for unit tests. PS:在实际代码中,数组是一个结构数组,必须迭代才能进行单元测试。
template<class T, size_t S>
void Check(T (&)[S]) {
cout << "Deduced size: " << S << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.