#include <iostream>
#include <array>
#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl
template<std::size_t Size>
void Print(std::array<int, Size>& arr) {
for (int i = 0; i < Size; i++) {
println(arr[i]);
}
}
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
Print(arr);
}
How does the size got passed to the function template without defining it like Print<5>(arr) ? (at line 7 "the actual template", at line 16 "calling the function")
How does the size got passed to the function template without defining it like
Print<5>(arr)?
It is thanks to template argument deduction. The size is deduced from the call Print(arr). Print() is a function template with a non-type template parameter (i.e., Size) of type std::size_t:
template<std::size_t Size>
void Print(std::array<int, Size>&);
That is, the template parameter Size is deduced to a value of type std::size_t, which corresponds to the second template argument of the std::array passed as a function argument when calling Print().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With