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.

5.2. PROVIDING TYPE INFORMATION 139<br />

The reader will imagine that implementations in libraries like MTL or GLAS will provide<br />

a larger interface in such classes. this short example is expressive enough to demonstrate the<br />

approach. However, the example is large enough to demonstrate the need of meta-programming<br />

in certain views.<br />

An object of this class can be handled like a matrix so that a template function use it as<br />

argument whereever a matrix is expected. The transposition is achieved by calling operator() in<br />

the referred object with switched indices. For every matrix object we can define a transposed<br />

view that behaves like a matrix<br />

mtl::dense2D A(3, 3);<br />

A= 2, 3, 4,<br />

5, 6, 7,<br />

8, 9, 10;<br />

tst::transposed view At(A);<br />

When we access At(i, j) we will get A(j, i). We even define a non-const access so that we can<br />

even change entries:<br />

At(2, 0)= 4.5;<br />

This operation sets A(0, 2) to 4.5.<br />

The definition of a transposed view object does not leed to particularly concise programs. For<br />

convience we define a function that returns the transposed view.<br />

template <br />

transposed view inline trans(Matrix& A)<br />

{<br />

return transposed view(A);<br />

}<br />

Now we can use the transposed elegantly in our scientific software, <strong>for</strong> instance in a matrix<br />

vector product:<br />

v= trans(A) ∗ q;<br />

In this case, a temporary view is created and used in the product. Since operator() from the<br />

view is inlined the transposed product will be as fast as with A itself.<br />

Dealing with Const-ness<br />

So far, so good. Problems arise if we build the transposed view of a constant matrix:<br />

const mtl::dense2D B(A);<br />

We still can create the transposed view of B but we cannot access its elements:<br />

std::cout ≪ ”tst::trans(B)(2, 0) = ” ≪ tst::trans(B)(2, 0) ≪ ’\n’; // error<br />

The compiler will tell us that it cannot initialize a ‘float&’ from a ‘const float’. If we look at the<br />

location of the error we will realize that this is line 9 in Listing 5.1. But we did the compiler<br />

used the non-constant version of the operator? In line 10 we defined an operator <strong>for</strong> constant<br />

objects which returns a constant reference and fits perfectly <strong>for</strong> this situation.

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

Saved successfully!

Ooh no, something went wrong!