I am confused by how C++ instantiate template. I have a piece of code:
template <class T, int arraySize>
void test1(T (&array)[arraySize])
{
cout << typeid(T).name() << endl;
}
template<class T>
void test2(T &array)
{
cout << typeid(T).name() << endl;
}
int main()
{
int abc[5];
test1(abc);
test2(abc);
return 0;
}
Here are my questions:
1. How does the size of array abc is passed to test1 (the parameter arraySize )?
2. How does C++ compiler determine the type of T in the two templates?
In test1 the compiler creates a template with T[arraySize] being its form.
When you call test1(abc) you are providing an input argument of type int[5] which the template matcher automatically matches.
However, if you were to write
then the compilation would fail and the compiler would claim that it has no template matching the test1(abc) function call or the test1< int,n >(abc) function call.
This is because the size of abc is now dynamically allocated and so the type of abc is a pointer which has a different type and hence no template could be matched to the above two calls.
The following code shows you some types