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.

108 CHAPTER 4. GENERIC PROGRAMMING<br />

really the object itself but only use it <strong>for</strong> the calculation, we can as well create an anonymous<br />

object and per<strong>for</strong>m the creation/construction and calcution in one expression:<br />

template <br />

typename abs functor::result type<br />

inline abs(const T& x)<br />

{<br />

return abs functor()(x);<br />

}<br />

In this expression we have two pairs of parentheses: the first one contains the arguments of the<br />

constructor, which are empty, and the arguments of the application operator, which is/are the<br />

argument(s) of the function. If would write:<br />

template <br />

typename abs functor::result type<br />

inline abs(const T& x)<br />

{<br />

return abs functor(x); // error<br />

}<br />

then x would be interpreted as argument of the constructor and an object of the functor class<br />

would be returned. 18<br />

Now we have to implement our functor classes:<br />

template <br />

struct abs functor<br />

{<br />

typedef T result type;<br />

};<br />

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

{<br />

return x < T(0) ? −x : x;<br />

}<br />

template <br />

struct abs functor<br />

{<br />

typedef T result type;<br />

};<br />

T operator()(const std::complex& x)<br />

{<br />

return sqrt(real(x)∗real(x) + imag(x)∗imag(x));<br />

}<br />

We wrote a general implementation that works <strong>for</strong> all fixed-point and floating-point types.<br />

18 Many years and versions ago, g++ tolerated this expression (sometimes) despite it is not standard-compliant.

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

Saved successfully!

Ooh no, something went wrong!