Docsity

Understanding Function and Class Templates in C++, Slides of Computer Science

Partial preview of the text

Download Understanding Function and Class Templates in C++ and more Slides Computer Science in PDF only on Docsity!

Templates

Templates

• A Template Defines the Content of a Family of

Data Types

• Two Types -- Function and Class Templates

Function Template -- Example

#include<stream.h>

//Template Function Definition template T maximum(T t1, T t2){

if (t1 > t2) {return t1;} else {return t2;}

} main(){

int a = 10, b = 15; float c = 20.0, d = 25.5;

cout << "Maximum Integer: " << maximum(a, b) << endl; cout << "Maximum Float: " << maximum(c, d) << endl;

//ERROR....Parameter Type Mismatch -- No Conversion cout << "Maximum: " << maximum(a, d) << endl;

//Explicit Prototype for Forced Conversion float maximum(float, float);

}^ cout << "Maximum: " << maximum(a, d) << endl; //FINE

Class Template

• Specifies a Generic Class and Uses it in the

Algorithm

• Proper Arguments Must be Supplied Before

Creating an Instance (or Object) Using the

Template Class

Class Template -- Stack Example -- Cont'd

OUTPUT WILL BE


Stack Size: 1 Top: 10