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?
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation.
To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>(float original); Template arguments may be omitted when the compiler can infer them.
Class template instantiationIn order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
Automatic Instantiation The bodies of template classes and inline (or static) template functions are always instantiated implicitly when their definitions are needed. Member functions of template classes are not instantiated until they are used. Other template items can be instantiated by using explicit instantiation.
arraySize
and T
are inferred from the type of the array
parameter. Since you pass an int[5]
, arraySize
and T
become 5
and int
, respectively, at compile time.If, for example, you declared int* abc = new int[5];
, your compiler would barf at the point you try to call test1(abc)
. Apart from a basic type-mismatch, int*
doesn't carry enough information to infer the size of the array.
It is called template argument deduction.
The type of abc
at call-site is : int(&)[5]
which has two info combined: int
and 5
. And the function template accepts argument of type T(&)[N]
, but the argument at call-site is, int(&)[5]
, so the compiler deduces that T
is int
and N
is 5
.
Read these:
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