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.

154 CHAPTER 5. META-PROGRAMMING<br />

Discussion 5.1 The drawback is that if the entries are accessed multiple times the sum is<br />

recomputed. On the other hand, most expressions are only used once and this is not a problem.<br />

An example where vector entries are accessed several times is A ∗ (x+y). Here, it is preferable<br />

to compute a true vector first instead of computing the matrix vector product on the expression<br />

template. 12<br />

To evaluate w= x + y we also need an assignment operator <strong>for</strong> vector sum:<br />

template class vector sum; // <strong>for</strong>ward declaration<br />

template <br />

class vector<br />

{ // ...<br />

vector& operator=(const vector sum& 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 />

};<br />

The assignment runs a loop over w and that. As that is an object of type vector sum the expression<br />

that[i] computes x[i] + y[i]. In contrast to the implementationn in Section 5.3.1 we have now<br />

• Only one loop;<br />

• No temporary vector;<br />

• No additional memory allocation and deallocation; and<br />

• No addional data reads and writes.<br />

In fact, the same operations are per<strong>for</strong>med as in the loop<br />

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

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

The cost to create a vector sum object is negligible. The object will be kept on the stack and does<br />

not require memory allocation. Even that little ef<strong>for</strong>t <strong>for</strong> creating the object will be optimized<br />

away by most compilers with static code analysis.<br />

What happens when we like to add three vectors? The naïve implementation from § 5.3.1<br />

returns a vector and this vector can be added to another vector. Our approach returns a<br />

vector sum and we have no addition <strong>for</strong> vector sum and vector. Thus we would need another ET<br />

class and an according operation:<br />

template <br />

class vector sum3<br />

{<br />

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

public:<br />

vector sum3(const vector& v1, const vector& v2, const vector& v3) : v1(v1), v2(v2), v3(v3)<br />

{<br />

assert(size(v1) == size(v2)); assert(size(v1) == size(v3));<br />

12 TODO: Shall we provide a solution <strong>for</strong> this as well? This something that is over-due in MTL4 anyway.

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

Saved successfully!

Ooh no, something went wrong!