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.

138 CHAPTER 5. META-PROGRAMMING<br />

We can now consider extending this definition to vectors and matrices, e.g., to determine the<br />

return type of a norm. The specialization reads<br />

template <br />

struct Magnitude<br />

{<br />

typedef T type; // not really perfect<br />

};<br />

However, if the value type of the vector is complex, its norm will not. Instead, we need the<br />

magitude type from the values:<br />

template <br />

struct Magnitude<br />

{<br />

typedef typename Magnitude::type type;<br />

};<br />

5.2.2 A const-clean View Example<br />

In this section, we look at an efficient and expressive implementation of a transposed matrix. If<br />

you compute the transposed of a matrix, many software packages return a new matrix object<br />

with the interchanged values. This is a quite expensive operation: it requires memory allocation<br />

and deallocation and often copying a lot of data.<br />

Writing a Simple View Class<br />

A much more efficient approach is implementing a ‘View’ of the existing object. We refer<br />

internally to the viewed object and just adapt its interface. This can be done very nicely <strong>for</strong><br />

the transposed of a matrix:<br />

1 template <br />

2 class transposed view<br />

3 {<br />

4 public:<br />

5 typedef typename mtl::Collection::value type value type;<br />

6 typedef typename mtl::Collection::size type size type;<br />

7<br />

8 transposed view(Matrix& A) : ref(A) {}<br />

9<br />

10 value type& operator()(size type r, size type c) { return ref(c, r); }<br />

11 const value type& operator()(size type r, size type c) const { return ref(c, r); }<br />

12<br />

13 private:<br />

14 Matrix& ref;<br />

15 };<br />

Listing 5.1: Simple view implementation<br />

We assume that the matrix class has an operator() taking two arguments <strong>for</strong> the row and column<br />

index respectively. We further suppose that type traits are defined <strong>for</strong> value type and size type.<br />

This is all we need to know about the referred matrix, 3 at least in this mini example.<br />

3 TODO: We should define a concept <strong>for</strong> it.

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

Saved successfully!

Ooh no, something went wrong!