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.

196 CHAPTER 6. INHERITANCE<br />

Another disadvantage of the implementation above is that we would need another proxy <strong>for</strong> the<br />

constant access.<br />

This is an interesting aspect of templates. It does not only enable writing type-parametric software<br />

but can also help to break mutual dependencies thanks to its post-poned code generation.<br />

By templetizing the proxy the dependency is gone:<br />

template <br />

class bracket proxy<br />

{<br />

public:<br />

bracket proxy(Matrix& A, int r) : A(A), r(r) {}<br />

Result& operator[](int c){ return A(r, c); }<br />

private:<br />

Matrix& A;<br />

int r;<br />

};<br />

class matrix<br />

{<br />

// ...<br />

bracket proxy operator[](int r)<br />

{<br />

return bracket proxy(∗this, r);<br />

}<br />

};<br />

With this implementation we can now write A[i][j] and it is realized by the binary operator()<br />

however this is implemented. Such a bracket operator is useful in every matrix class and the<br />

implementation will be always the same.<br />

For this reason we like to have this implementation only once in our code base and reuse<br />

whereever appropriate. The only way to achieve this is with the CRTP paradigm:<br />

template <br />

class bracket proxy<br />

{<br />

public:<br />

bracket proxy(Matrix& A, int r) : A(A), r(r) {}<br />

Result& operator[](int c){ return A(r, c); }<br />

private:<br />

Matrix& A;<br />

int r;<br />

};<br />

template <br />

class crtp matrix<br />

{<br />

public:<br />

bracket proxy operator[](int r)<br />

{<br />

return bracket proxy(static cast(∗this), r);<br />

}

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

Saved successfully!

Ooh no, something went wrong!