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

The concept of function and class templates in c++ programming language. Function templates define a generic class and use it in the function algorithm, allowing the compiler to create appropriate function definitions during a function call invocation. Class templates specify a generic class and use it in the algorithm, requiring proper arguments to be supplied before creating an instance. Examples of function and class templates using the docsity.com platform.

Typology: Slides

2012/2013

Uploaded on 03/21/2013

dharmaraaj
dharmaraaj 🇮🇳

4.4

(68)

145 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Templates
Docsity.com
pf3
pf4
pf5

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