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.7. NON-TYPE PARAMETERS FOR TEMPLATES 109<br />

4.7 Non-Type Parameters <strong>for</strong> Templates<br />

So far, we used template arguments only <strong>for</strong> types. Values can be template arguments as well.<br />

Not all values but only integral types, i.e. fixed point numbers and bool.<br />

Very popular is the definition of short vectors and small matrices with size arguments as template<br />

parameters, <strong>for</strong> instance:<br />

template <br />

class fsize vector<br />

{<br />

typedef fsize vector self;<br />

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

public:<br />

typedef T value type;<br />

const static int my size= Size;<br />

fsize vector() {}<br />

fsize vector( const self& that )<br />

{<br />

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

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

}<br />

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

{<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 />

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

{<br />

self sum;<br />

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

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

return sum ;<br />

}<br />

private:

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

Saved successfully!

Ooh no, something went wrong!