在此代码中:
#include <cstddef>
#include <array>
#include <iostream>
// here
template <typename T, std::size_t size>
void printArray(const std::array<T, size>& myArray) {
for (auto element : myArray)
std::cout << element << ' ';
std::cout << '\n';
}
int main() {
std::array myArray1{ 9.0, 7.2, 5.4, 3.6, 1.8 };
printArray(myArray1);
// shouldn't this line be
printArray<double, 5>(myArray1)
return 0;
}
我知道模板和函数是如何工作的,但我不明白的是std::size_t
在第16行的什么地方被传递进来,我知道模板会推导出类型,它会自动传递数组大小吗?
1条答案
按热度按时间mspsb9vt1#
我知道模板会推导出类型。它也会自动传递数组大小吗?
是的,模板非类型参数
size
的值将从函数参数的类型推导出来,与推导模板类型参数T
相同。