在数组函数模板头中使用std::size_t(C++)

wkyowqbh  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(97)

在此代码中:

#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行的什么地方被传递进来,我知道模板会推导出类型,它会自动传递数组大小吗?

mspsb9vt

mspsb9vt1#

我知道模板会推导出类型。它也会自动传递数组大小吗?
是的,模板非类型参数size的值将从函数参数的类型推导出来,与推导模板类型参数T相同。

相关问题