Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use of std::size_t in array function template header (C++)

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading