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.

112 CHAPTER 4. GENERIC PROGRAMMING<br />

Note that the function finite difference takes an arbitrary function (from double to double) as<br />

argument.<br />

Now suppose we want to compute the second order derivative. It would make sense to call<br />

finite difference with finite difference as argument. Un<strong>for</strong>tunately this is not possible since we have<br />

three arguments in this function and the first argument of finite difference only accepts a function<br />

with a single argument.<br />

For this reason, we can use ‘functors’. Functors — not to confuse with functors from category<br />

theory — are either functions or objects of classes providing operator(). This means that<br />

‘functors’ are things which can be called liked functions but are not necessarily functions.<br />

Using objects of a class providing operator() has the additional advantage that it can use an<br />

internal state in terms of member variables. 21<br />

For our example, the functor could be implemented as follows:<br />

struct sin plus cos<br />

{<br />

double operator() (double x) const<br />

{<br />

return sin(x) + cos(x) ;<br />

}<br />

};<br />

but we could also consider a functor with an parameter like this:<br />

class para sin plus cos<br />

{<br />

public:<br />

para sin plus cos(double parameter) : parameter(parameter) {}<br />

double operator() (double x) const<br />

{<br />

return sin(parameter ∗ x) + cos(x) ;<br />

}<br />

private:<br />

double parameter;<br />

} ;<br />

How can we use the functor in a function? We want to be able to pass objects of both sin plus cos<br />

and para sin plus cos to our finite difference function. There are two possible solutions: inheritance<br />

and generic programming, which we now discuss.<br />

4.8.1 Functors via inheritance<br />

TODO: Better as counter-example in OO chapter. We haven’t introduced virtual functions<br />

yet.<br />

Let us first rewrite our function finite difference using an abstract base class.<br />

21 TODO: Do we want the following sentences?: Functors can encapsulate C and C ++ function pointers<br />

employing the concepts templates and polymorphism. All the functions must have the same return-type and<br />

calling parameters.

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

Saved successfully!

Ooh no, something went wrong!