3 Tips for Using Templates in C++ - dummies

3 Tips for Using Templates in C++

By Stephen R. Davis

A function template enables you to write something that looks like a function but uses one or more type holders that C++ converts into a true type at compile time. You should remember a few things when using templates.

  1. First, no code is generated for a template. (Code is generated after the template is converted into a concrete class or function.) This implies that a .cpp source file is almost never associated with a class template.

    The entire class template definition, including all the member functions, are usually contained in an include file so that it can be available for the compiler to expand.

  2. Second, a class template does not consume memory. Therefore, there is no penalty for creating class templates if they are never instanced. On the other hand, a class template uses memory every time it is instanced. Thus, the code for Array<Student> consumes memory even if Array<int> already exists.

  3. Finally, a class template cannot be compiled and checked for errors until it is converted into a real class. Thus, a program that references the class template Array<T> might compile even though Array<T> contains obvious syntax errors. The errors won′t appear until a class such as Array<int> or Array<Student> is created.

Creating a function from a template is called instantiating the template.