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.

188 CHAPTER 6. INHERITANCE<br />

{<br />

}<br />

std::cout ≪ ”CG\n”;<br />

void bicg(const matrix& A, const vector& b, vector& x)<br />

{<br />

std::cout ≪ ”BiCG\n”;<br />

}<br />

int main (int argc, char∗ argv[])<br />

{<br />

matrix A;<br />

vector b, x;<br />

}<br />

switch (std::atoi(argv[1])) {<br />

case 0: cg(A, b, x); break;<br />

case 1: bicg(A, b, x); break;<br />

}<br />

return 0 ;<br />

This works but it is not scalable with respect to source code complexity. If we call the solver<br />

with other vectors and matrices somewhere else we must copy the whole switch-case-block<br />

<strong>for</strong> each argument combination. This can avoided by encapsulating the block into a function<br />

and call this one with different arguments. More complicated is to different preconditioners<br />

(diagonal, ILU, IC, . . . ) that are also dynamically selected. Shall we copy a switch block <strong>for</strong><br />

the preconditioners into each case block of the solvers?<br />

An elegant solution is an abstract solver class and derived classes <strong>for</strong> the solvers:<br />

struct solver<br />

{<br />

virtual void operator()(const matrix& A, const vector& b, vector& x)= 0;<br />

virtual ∼solver() {}<br />

};<br />

// potentially templatize<br />

struct cg solver : solver<br />

{<br />

void operator()(const matrix& A, const vector& b, vector& x) { cg(A, b, x); }<br />

};<br />

struct bicg solver : solver<br />

{<br />

void operator()(const matrix& A, const vector& b, vector& x) { bicg(A, b, x); }<br />

};<br />

In the application we can define one or multiple pointers of type solver and assign them the<br />

desired solver:<br />

// Factory<br />

solver∗ my solver= 0;<br />

switch (std::atoi(argv[1])) {<br />

case 0: my solver= new cg solver; break;<br />

case 1: my solver= new bicg solver; break;

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

Saved successfully!

Ooh no, something went wrong!