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.

144 CHAPTER 5. META-PROGRAMMING<br />

The Solution<br />

Now we have all we need to revise the view from Listing 5.1. The problem was that we returned<br />

an entry of a constant matrix as mutable reference. To avoid this we can try to make the<br />

mutable access operator disappear in the view when the referred matrix is constant. This is<br />

possible but too complicated <strong>for</strong> the momemt. We will come back to this in Section 5.2.4.<br />

An easier solution is to keep both the mutable and the constant access operator but choose the<br />

return type of the <strong>for</strong>mer depending on the type of the template argument:<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 private:<br />

8 typedef typename if ::type vref type;<br />

12 public:<br />

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

14<br />

15 vref type operator()(size type r, size type c) { return ref(c, r); }<br />

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

17<br />

18 private:<br />

19 Matrix& ref;<br />

20 };<br />

Listing 5.3: Const-safe view implementation<br />

This implementation returns a constant reference in line 15 when the referred matrix is constant<br />

and a mutable referrence <strong>for</strong> mutable referred matrix. Let us see if this is what we need. For<br />

mutable matrix references, the return type of operator() depends on the constancy of the view<br />

object:<br />

• If the view object is mutable (line 15) then operator() returns a mutable reference (line 10);<br />

and<br />

• If the view object is constant (line 16) then operator() returns a constant reference.<br />

This is the same behavior as in Listing 5.1.<br />

If the matrix reference is constant, then a constant reference is always returned:<br />

• If the view object is mutable (line 15) then operator() returns a mutable reference (line 9);<br />

and<br />

• If the view object is constant (line 16) then operator() returns a constant reference.<br />

Altogether, we implemented a view object that provides read and write access whereever appropriate<br />

and disables it where inappropriate.

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

Saved successfully!

Ooh no, something went wrong!