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.

150 CHAPTER 5. META-PROGRAMMING<br />

5.3 Expression Templates<br />

Scientific software has usually strong per<strong>for</strong>mance requirements — especially those problems<br />

we tackle with C ++. Many large-scale simulations of physical, chemical, or biological processes<br />

run <strong>for</strong> weeks or months and everybody is glad if at least a part of this very long execution<br />

times can be safed. Such safings are often at the price of readable and maintainable program<br />

sources. In Section 5.3.1 we will show a simple implementation of an operator and discuss why<br />

this is not efficient and in the remainder of Section 5.3 we will demonstrate how to improve to<br />

improve the per<strong>for</strong>mance without sacrificing the natural notation.<br />

5.3.1 Simple Operator Implementation<br />

Assume we have an application with vector addition. We want <strong>for</strong> instance write an expression<br />

of the following <strong>for</strong>m <strong>for</strong> vectors w, x, y and z:<br />

w = x + y + z;<br />

Say, we have a vector class as in Section 4.3:<br />

template <br />

class vector<br />

{<br />

public:<br />

explicit vector(int size) : my size(size), data(new T[my size]) {}<br />

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

};<br />

friend int size(const vector& x) { return x.my size; }<br />

const T& operator[](int i) const { check index(i); return data[i]; }<br />

T& operator[](int i) { check index(i); return data[i]; }<br />

// ...<br />

We can of course provide an operator <strong>for</strong> adding such vectors:<br />

template <br />

vector inline operator+(const vector& x, const vector& y)<br />

{<br />

x.check size(size(y));<br />

vector sum(size(x));<br />

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

sum[i] = x[i] + y[i];<br />

return sum;<br />

}<br />

A short test program checks that everything works:<br />

int main()<br />

{<br />

vector x(4), y(4), z(4), w(4);<br />

x[0]= x[1]= 1.0; x[2]= 2.0; x[3] = −3.0;<br />

y[0]= y[1]= 1.7; y[2]= 4.0; y[3] = −6.0;<br />

z[0]= z[1]= 4.1; z[2]= 2.6; z[3] = 11.0;

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

Saved successfully!

Ooh no, something went wrong!