03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

96 CHAPTER 4. GENERIC PROGRAMMING<br />

vector( const vector& that )<br />

: my size(that.my size), data( new T[my size] )<br />

{<br />

<strong>for</strong> (int i= 0; i < my size; ++i)<br />

data[i]= that.data[i];<br />

}<br />

∼vector() { if (data) delete [] data ; }<br />

vector& operator=( const vector& that )<br />

{<br />

check size(that.my size);<br />

<strong>for</strong> (int i= 0; i < my size; ++i)<br />

data[i]= that.data[i];<br />

}<br />

int size() const { return my size ; }<br />

const T& operator[]( int i ) const<br />

{<br />

check index(i);<br />

return data[i];<br />

}<br />

T& operator[]( int i )<br />

{<br />

check index(i);<br />

return data[i] ;<br />

}<br />

vector operator+( const vector& that ) const<br />

{<br />

check size(that.my size);<br />

vector sum(my size);<br />

<strong>for</strong> (int i= 0; i < my size; ++i)<br />

sum[i]= data[i] + that[i];<br />

return sum ;<br />

}<br />

private:<br />

int my size ;<br />

T∗ data ;<br />

};<br />

Listing 4.1: Template vector class<br />

The template class is not essentially different to a non-template class. There is only the extra<br />

parameter T as placeholder <strong>for</strong> the type that the class is used with.<br />

We have member variables like my size and member functions size() that are not affected by<br />

the template parameter. Other functions like the access operator or the first constructor are<br />

parametrized. However the difference is minimal, whereever we had double (or another type)<br />

be<strong>for</strong>e we put now the type parameter T, e.g. <strong>for</strong> return types or within new. Likewise our<br />

member variables and constants can be parametrized by T as <strong>for</strong> data. Even program parts<br />

that use generic functions or data can be often implemented without explicitly stating the

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!