Docsity

Object-Oriented Programming: Templates, Functions, and Non-Type Parameters, Slides of Object Oriented Programming

Partial preview of the text

Download Object-Oriented Programming: Templates, Functions, and Non-Type Parameters and more Slides Object Oriented Programming in PDF only on Docsity!

ObjectObject--Oriented ProgrammingOriented Programming

(OOP)(OOP)

Lecture No. 36 Lecture No. 36

RecapRecap – –Template SpecializationsTemplate Specializations

► ► A class template may not handle all theA class template may not handle all the

types successfully types successfully

► ► Explicit specializations are required to dealExplicit specializations are required to deal

such types such types

ExampleExample – – Partial SpecializationPartial Specialization

template< class T > template< class T >

class Vector { }; class Vector { };

template< class T > template< class T >

class Vector< T* > { }; class Vector< T* > { };

ExampleExample – – Complete SpecializationComplete Specialization

template< class T > template< class T >

class Vector { }; class Vector { };

template< > template< >

class Vector< char* > { }; class Vector< char* > { };

ExampleExample

► ► Consider the following templateConsider the following template

template< typename T > template< typename T > bool isEqual( T x, T y ) { bool isEqual( T x, T y ) { return ( x == y ); return ( x == y ); } }

Partial SpecializationPartial Specialization

► ► Following partial specialization deals withFollowing partial specialization deals with

pointers to objects pointers to objects

template< typename T > template< typename T > bool isEqual( T* x, T* y ) { bool isEqual( T* x, T* y ) { return ( *x == *y ); return ( *x == *y ); } }

ExampleExample – – NonNon--type Parameterstype Parameters

template< class T > template< class T >

Array::Array() { Array::Array() {

if (size > 0) if (size > 0) ptr = new T[size]; ptr = new T[size]; else else ptr = NULL; ptr = NULL;

} }

ExampleExample – – NonNon--type Parameterstype Parameters

template< class T, int SIZE > template< class T, int SIZE > class Array { class Array { private: private: T ptr[SIZE]; T ptr[SIZE]; public: public: Array(); Array(); … … }; };

Default Type ParametersDefault Type Parameters

► ► A type parameter can specify a default typeA type parameter can specify a default type

template< class T = int > template< class T = int > class Vector { class Vector { … … } }

Vector< > v; Vector< > v; // Vector< int > v;// Vector< int > v;