template <typename list_type>
int len(list_type list) {
std::cout << sizeof(list);
return (sizeof(list) / sizeof(list[1]));
}
int main() {
int list[5] = {1, 2 ,3 ,5 ,4};
std::cout << sizeof(list) << "\n";
len(list);
}
当我运行程序时,我得到:20
then 4
。尽管清单相同,为什么会有区别?
数组衰减为指针。
list
是int*
inlen()
和int[5]
in main
。
如此处所述,有两个可能的修复:
如果使用引用,它将起作用(指针不会衰减),但是您仍然必须计算元素数:
#include <iostream>
template <typename list_type>
int len(list_type &list) {
std::cout << sizeof(list) << '\n';
return (sizeof(list) / sizeof(list[1]));
}
int main() {
int list[5] = {1, 2 ,3 ,5 ,4};
std::cout << sizeof(list) << "\n";
auto element_count = len(list);
std::cout << "There are " << element_count << " elements in the list.\n";
}
对于第二个选项,您将在编译时获得数组的大小:
#include <iostream>
template <typename list_type, size_t N>
int len(list_type (&list) [N]) {
std::cout << sizeof(list) << '\n';
return N;
}
int main() {
int list[5] = {1, 2 ,3 ,5 ,4};
std::cout << sizeof(list) << "\n";
auto element_count = len(list);
std::cout << "There are " << element_count << " elements in the list.\n";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句