Docsity

Class Template Specialization - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Class Template Specialization - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 35

Member Templates

  • A class or class template can have

member functions that are themselves

templates

…Member Templates

int main() {

Complex< float > fc( 0, 0 ); Complex< double > dc = fc; // Error return 0;

}

Because

class Complex {

double real, imag;

public:

Complex( double r, double im ) : real(r), imag(im) {} Complex(const Complex& c) : real( c.real ), imag( c.imag ) {} …

};

…Member Templates

int main() {

Complex< float > fc( 0, 0 ); Complex< double > dc = fc; // OK return 0;

}

Because

class Complex {

double real, imag;

public:

Complex( double r, double im ) : real(r), imag(im) {} template Complex(const Complex& c) : real( c.real ), imag( c.imag ) {} …

};

Class Template Specialization

  • Like function templates, a class template

may not handle all the types successfully

  • Explicit specializations are provided to

handle such types

…Class Template Specialization

int main() {

Vector< int > iv1( 2 ); iv1[0] = 15; iv1[1] = 27; Vector< int > iv2( iv1 ); Vector< int > iv3( 2 ); iv3 = iv1; return 0;

}

…Class Template Specialization

template<>

class Vector< char* > {

private:

int size; char** ptr;

public:

// Vector< char* >( int = 10 ); Vector( int = 10 ); Vector( const Vector< char* >& ); virtual ~Vector();

…Class Template Specialization

int getSize() const; const Vector< char* >& operator =( const Vector< char* >& ); const char& operator ; void insert( char, int );

};

…Class Template Specialization

template<>

Vector< char* >::Vector(

const Vector& copy ) {

size = copy.getSize(); if ( size == 0 ) { ptr = 0; return; }

…Class Template Specialization

ptr = new char*[size]; for (int i = 0; i < size; i++) if ( copy.ptr[i] != 0 ) { ptr[i] = new char[ strlen( copy.ptr[i] ) + 1 ]; strcpy(ptr[i], copy.ptr[i]); } else ptr[i] = 0;

}

…Class Template Specialization

template<>

int Vector::getSize() const {

return size;

}

…Class Template Specialization

template<>

const Vector& Vector::

operator=(const Vector& right)

{

if ( this == &right ) return *this; for (int i = 0; i < size; i++) delete [] ptr[i]; delete [] ptr;