如何模板函数“知道”作为模板参数给定的数组的大小? [英] How can a template function 'know' the size of the array given as template argument?
问题描述
在下面的C ++代码中,模板化的Check函数给出了一个不是我想要的输出:它是1而不是3.我怀疑K映射到 int *
,而不是 int [3]
(是类型?)。我想它给我相同的输出比第二个(非模板)函数,我明确给出的数组的大小...
使用短宏,有没有办法写一个接受单个参数但仍知道数组大小的Check函数。
# include< iostream>
using namespace std;
int data [] = {1,2,3};
template< class K>
void Check(K data){
cout<< 推导的大小:< sizeof(data)/ sizeof(int)< endl;
}
void Check(int *,int sizeofData){
cout< 正确大小:< sizeofData / sizeof(int)< endl;
}
int main(){
Check(data);
检查(data,sizeof(data));
}
感谢。
PS:在实际代码中,数组是一个结构体数组,在进行单元测试时必须重复。
p> template< class T,size_t S>
void Check(T(&)[S]){
cout<< 推导的大小:< S<< endl;
}
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?). 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?
#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.
template<class T, size_t S>
void Check(T (&)[S]) {
cout << "Deduced size: " << S << endl;
}
这篇关于如何模板函数“知道”作为模板参数给定的数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!