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.

156 CHAPTER 5. META-PROGRAMMING<br />

};<br />

const V2& v2;<br />

This is rather straight<strong>for</strong>ward. The only issue is what type to return in operator[]? For this<br />

we must define value type in each class — more flexible would be an external type trait. In<br />

vector sum we take the value type of the first argument which can itself be taken from another<br />

class.<br />

template <br />

class vector sum<br />

{<br />

// ...<br />

typedef typename V1::value type value type;<br />

};<br />

value type operator[](int i) const { check index(i); return v1[i] + v2[i]; }<br />

To assign such an expression to a vector we can also generalize the assign operator:<br />

template <br />

class vector<br />

{<br />

public:<br />

typedef T value type;<br />

};<br />

template <br />

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

{<br />

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

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

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

return ∗this;<br />

}<br />

This assigment can also handle vector as argument and we can omit the standard assignment<br />

operator.<br />

Advantages of expression templates: Although the availability of operator overloading<br />

in C ++ resulted in notationally nicer code, the scientific community refused to give up programming<br />

in Fortran or to implement the loops directly in C/C ++. The reason was that the<br />

traditional operator implementations were too expensive. Due to the overhead of the creation<br />

of temporary variables and the copying of vector and matrix objects, C ++ could not compete<br />

with the per<strong>for</strong>mance of programs written in Fortran. This problem has now been resolved<br />

by the introduction of generics and expression templates. Now it is possible to write efficient<br />

scientific programs in a notationally convenient manner.<br />

5.4 Meta-Tuning: Write Your Own Compiler Optimization<br />

Compiler technology is progressing and provides us an increasing number of optimization techniques.<br />

Ideally, everyone writes his software in the way it is the easiest <strong>for</strong> him and the compiler

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

Saved successfully!

Ooh no, something went wrong!