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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

4.3. GENERIC CLASSES 95<br />

+= operator to variables of type T. This operator is defined <strong>for</strong> int and double types. This<br />

implies that the following main program will compile without the need <strong>for</strong> another definition of<br />

the accumulate function:<br />

int main()<br />

{<br />

const int n = 10;<br />

float a[n] ;<br />

int b[n] ;<br />

<strong>for</strong> (int i= 0; i < n; ++i) {<br />

a[i]= float(i) + 1.0f;<br />

b[i]= i + 1;<br />

}<br />

float s= accumulate(a, a + n);<br />

int r= accumulate(b, b + n);<br />

return 0;<br />

}<br />

As well as in the previous example we do not need to indicate explicitly that T is double or int.<br />

The compiler deduces this <strong>for</strong> us from the function. We can, however, fill in the correct value<br />

of the type as follows:<br />

int r = accumulate(b, b+n);<br />

If you fill in the wrong type the compiler will give you a type error by saying that no matching<br />

function exists.<br />

4.3 Generic classes<br />

In the previous section, we described the use of templates to create generic functions. Templates<br />

can also be used to create generic classes, that define a certain behaviour that is independent<br />

of the types they operate on. Good candidates are <strong>for</strong> example container classes like vectors,<br />

matrices and lists. We can also extend the complex class with a parametric value type but we<br />

spent already so much time with it that we will now look at something else.<br />

Let us write a generic vector class. 4 First we just implement a class with the most fundamental<br />

operators:<br />

template <br />

class vector<br />

{<br />

void check size(int that size) const { assert(my size == that size); }<br />

void check index(int i) const { assert(i >= 0 && i < my size); }<br />

public:<br />

explicit vector(int size)<br />

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

{}<br />

vector()<br />

: my size(0), data(0)<br />

{}<br />

4 In the sense of linear algebra not like STL vector.

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

Saved successfully!

Ooh no, something went wrong!