How to write a template function that takes an array and an int specifying array size
arrays, c++, function, template-function
Solution
The correct way to write it is
Live On Coliru
#include <iostream>
template <typename T, size_t size> void print(const T (&array)[size])
{
for(size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
}
int main() {
int arr[] = { 1,2,3,4,99};
print(arr);
}
Prints
1 2 3 4 99
Problem
For a university exercise, I have been asked to write a template function "print();", which takes two arguments, 1: an array of a generic type, and 2: an int specifying the size of the array. The function should then print out every item in the array to the console. I am having some trouble with the function arguments. The code I currently have is: ``` template <typename Type> Type print (Type a, Type b) { Type items; Type array; a = array; b = items; for (int i = 0; i < items; i++) { std::cout << std::endl << "The element of the index " << i << " is " << array << std::endl; std::cout << std::endl; } ``` and in main(): ``` print(Array[], 10); ``` Obviously putting Array as an argument isn't returning a value, so I am not sure what else to do. Any ideas?