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.

120 CHAPTER 4. GENERIC PROGRAMMING<br />

4.8.3 The function accumulate with a functor argument<br />

TODO: Again, I don’t like the use of pointers here — Peter<br />

Recall the function accumulate from section 4.2.1 that we used to introduce Generic Programming.<br />

In this section, we will generalize this function. We introduce a binary functor (concept<br />

BinaryFunctor) that implements an operation on two arguments as function or callable class<br />

object. 27 Then we can accumulate values with respect to this binary operation:<br />

template <br />

T accumulate( T∗ a, T∗ a end, T init, BinaryFunctor op ) {<br />

T sum( init ) ;<br />

<strong>for</strong> ( ; a!=a end; ++a ) {<br />

sum = op( sum, ∗a ) ;<br />

}<br />

return sum ;<br />

}<br />

The concept BinaryFunctor is defined as follows: 28<br />

• Let op be of type BinaryFunctor.<br />

– has the method op( first argument type, second argument type ) with result type being<br />

convertible to T. T should be convertible to the first and second argument types.<br />

From this generic example, it is quite clear that the conceptual conditions are becoming complicated<br />

when we are mixing types. Usually, we make sure that the first argument type, second<br />

argument type and result type are the same, but strictly speaking, this is not required, since<br />

the compiler is allowed to per<strong>for</strong>m conversions.<br />

The main program could be as follows:<br />

struct sum functor<br />

{<br />

double operator() ( double a, double b ) const {<br />

return a + b ;<br />

}<br />

} ;<br />

struct product functor<br />

{<br />

double operator() ( double a, double b ) const {<br />

return a ∗ b ;<br />

}<br />

} ;<br />

int main()<br />

{<br />

int n=10;<br />

double a[n] ;<br />

double s = accumulate( a, a+n, 0.0, sum functor() ) ;<br />

s = accumulate( a, a+n, 1.0, product functor() ) ;<br />

}<br />

27 TODO: Introduce term.<br />

28 TODO: revisit

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

Saved successfully!

Ooh no, something went wrong!