Home > Enterprise >  Use of std::size_t in array function template header (C )
Use of std::size_t in array function template header (C )

Time:12-16

In this code:

#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;
}

I understand how the template and function works, but what I don't understand is where std::size_t is being passed in on line 16. I know templates will deduce the type. Will it automatically pass in the array size, too?

CodePudding user response:

I know templates will deduce the type. Will it automatically pass in the array size, too?

Yes, the value of the template non-type parameter size will be deduced from the type of the function argument, same as the template type parameter T is deduced.

  • Related