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.

118 CHAPTER 4. GENERIC PROGRAMMING<br />

T operator()(const T& x) const<br />

{<br />

return ( fp(x+h) − fp(x) ) / h ;<br />

}<br />

Likewise <strong>for</strong> even N, only the backward difference is computed without testing.<br />

If nothing else we learned something about C ++ and we are confirmed in the<br />

Truism<br />

Not even the coolest programming can substitute <strong>for</strong> solid mathematics.<br />

In the end, this script is primarily about programming. To improve the expressiveness of our<br />

software, functors are an extremely powerful approach. We have seen how to take an arbitrary<br />

unary function and construct a unary function that approximates its derivative or a higher-order<br />

derivative.<br />

If we do not know the type of a function or we do not like to bother with it we can write a<br />

convenience function that detects the type automatically:<br />

template <br />

nth derivative<br />

inline make nth derivative(const F& f, const T& h)<br />

{<br />

return nth derivative(f, h);<br />

}<br />

Here F and T are types of function arguments and can be detected by the compiler. The only<br />

template argument that the compiler does not detect is N. Note that such arguments must be<br />

at the beginning of the template argument list and the compiler-detected at the end. There<strong>for</strong>e<br />

the following template function is wrong:<br />

template // error<br />

nth derivative<br />

inline make nth derivative(const F& f, const T& h)<br />

{<br />

return nth derivative(f, h);<br />

}<br />

If you call this one, the compiler will complain that it cannot detect N. This leads us to the<br />

question how we call this function. Of course, we can explicitly declare all argument types:<br />

make nth derivative(sin 1, 0.00001);<br />

But this is exactly what we wanted to avoid with implementing this function. As said, F and T<br />

can be detected by the compiler and we only need to provide N:<br />

make nth derivative(sin 1, 0.00001);<br />

What is this expression good <strong>for</strong>? Written like this, not much. It creates a function that will<br />

be immediately destroyed. If it is a function we should be able to call it with an argument:

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

Saved successfully!

Ooh no, something went wrong!