class: titlepage, center, middle, subsection # Templates --- .left-column[ ## Templates ### - Basics ] .right-column[ A template is a class which is parameterized in one or more * Types * Constants * Policies During implementation there are only place-holders in effect. The client supplies the actual values during instantiation. The most typical use is for STL container classes, like * ``std::vector`` * ``std::list`` * ... But there are many other practical applications. ] --- .left-column[ ## C++ Templates ### - Basics ### - UML ] .right-column[ The UML notation for a template is * an ordinary class symbol (rectangle) * with another class symbol overlayed, slightly shifted top-right [See Info-Graphic: UML Classes and Relations](http://www.tbfe.de/data/uploads/diagrams/uml-classesandrelations.png) ] ] --- .left-column[ ## Templates ### - Basics ### - UML ### - C++ ] .right-column[ Templates come in two flavours: * Template functions * Template classes In both case declarations and definitions need to introduce formal names for the parametrized information. * This is done after the keyword ``template`` in a list enclosed in angle brackets. * The parametrization applies to the function or class that directly follows. * Therefore needs to be repeated for member function defined outside of their class. ] --- #### Template - Function - Example (Definition) The following function has three arguments, the first two are fixed in type, the third is parametrized. In the function implementation ``T``may be used as any ordinary type, e.g. to allocate a local temporary. ~~~ template
void foo(int x, char *cp, T other) { T tmp{other}; } ~~~ --- #### Template - Function - Example (Call) When calling this function, the type of the third argument is used by the compiler to deduce the type of ``T``: * In this call ``T`` would be deduced to have type ``double``: ~~~ double d; foo(12, "hello", d); ~~~ * In this call ``T`` would be deduced to have type ``std:string``: ~~~ std::string s; foo(12, "hello", s); ~~~ --- #### Template - Class - Example (Definition) The following class is parametrized in a type and a size. An example use is to define an array inside the class: ~~~ template
class RingBuffer { ElementType data[MaxElements]; // ... } ~~~ --- #### Template - Class - Example (Instantation) When instantiating ``RingBuffer`` objects the template arguments must be given concrete values: * In this instantiation there would be 20 Elements of type ``int``: ~~~ RingBuffer
rb; ~~~ * In this instantiation there would be 100 Elements of type ``std::string``: ~~~ RingBuffer
rb2; ~~~ --- # Resources --- name: info-graphics ## Info-Graphics ---