I am learning templates in C++ using the books listed here. So trying out(writing) different examples to clear my concepts. In particular, i learned that we can use templates to pass array by reference as shown below:
#include <iostream>
template<unsigned int N>
void printSize(double (&arr)[N])
{
std::cout<<"size is: "<<N<<std::endl;
}
int main()
{
double arr1[] = {1,2,3};
printSize(arr1); //this works as expected
}
The above is just a contrived example which i understand. While the example given below, i am unable to understand.
#include <iostream>
template<unsigned int N>
void printSizeTwo(double (&arr)[N+1]) //is this valid? I mean what will N+1 mean here if it is indeed valid.
{
std::cout<<"size is: "<<N<<std::endl;
}
int main()
{
double arr1[] = {1,2,3};
printSizeTwo(arr1); //why doesn't this call work?
}
My question is that in my second code snippet, is writing N+1
valid? If yes, then what does it mean that is., how is it different from the first code snippet where we have only N
instead of N+1
. Basically, i want to understand why the call to printSizeTwo(arr1)
doesn't work and how can i make it work.