Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates instantiation in C++

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?

like image 717
cheng Avatar asked Sep 20 '11 11:09

cheng


People also ask

What is a template instantiation?

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.

How do I instantiate a template class?

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.

Why we need to instantiate the template?

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).

When the templates are usually instantiated?

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.


2 Answers

  1. There is no parameter passing in the normal sense, since template parameters are resolved at compile time.
  2. Both 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.

like image 129
Marcelo Cantos Avatar answered Oct 27 '22 11:10

Marcelo Cantos


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:

  • The C++ Template Argument Deduction (at ACCU)
  • Template argument deduction (C++ only) (at IBM)
like image 27
Nawaz Avatar answered Oct 27 '22 10:10

Nawaz