Presentation is loading. Please wait.

Presentation is loading. Please wait.

Templates C++ template

Similar presentations


Presentation on theme: "Templates C++ template"— Presentation transcript:

1 Templates C++ template
A function or a class that has type independent elements The unspecified types are assigned at compile time Depending on how the template is used A form of compile-time polymorphism

2 Function templates Identified with the construct
template <class T> Or template <typename T> Placed before the template function “T” is a placeholder for the type It is user defined, can be anything Used in the template as a “type” // swaps the values for two // elements of type “T” template <class T> void swapValues(T &x, T &y) { T temp; temp=y; y=x; x=temp; }

3 Function templates (usage)
Using a template function Specify the type within angel braces “<>” Examples: swapValues<int>(i,j); // swap 2 integers swapValues<float>(x,y); // swap 2 floats swapValues<string>(a,b); // swap 2 strings Compiler will generate the appropriate function(s) // swaps the values for two // elements of type “T” template <class T> void swapValues(T &x, T &y) { T temp; temp=y; y=x; x=temp; }

4 Template class Similar to creating a template function
Use the template keyword construct to identify both the class and any necessary data members as template items template <class T> Or template <typename T> “T” is a placeholder for the type It is user defined (“T” is common, but it can be anything) Used in the template as a “type”

5 Template Class Example
#ifndef MYCLASS_H #define MYCLASS_H template <typename eltType> class MyClass { public: MyClass(); // default constructor! void setValue(int v) ; eltType getValue(); private: eltType value; }; MyClass<eltType>::MyClass() { value=0; } void MyClass <eltType> ::setValue(eltType v) { value= v; eltType MyClass <eltType> ::getValue() { return value; #endif A templated class is identified with the template keyword construct As are all member methods And the class name with the scope resolution operator (::) Template type (eltType) is used wherever the template data member is needed Usage is similar to a template function MyClass<int> I; Creates an instance I to hold an integer MyClass<float> F; Creates an instance F to hold a float F.setValue(3.14); // set the float value

6 Compilation Simplest approach is to put template functions and classes in a header (.h) file Include the header in any file that uses the template Do not use separate header and implementation files for classes Do not compile the template files separately This approach allows the compiler to create the necessary function/class types upon compilation Otherwise, if the templates are compiled separately, class/function prototypes will need to be defined for all types used in the target program So that all used function/template types are available when linking occurs


Download ppt "Templates C++ template"

Similar presentations


Ads by Google