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.

7.4. FUNCTIONAL PROGRAMMING 211<br />

}<br />

};<br />

stream ≪ func(arg);<br />

The only thing we have to do by now is to write an appropriate object generator around in<br />

order to persuade the C ++ syntax to accept something like the first line of code of this chapter.<br />

template<br />

output function object<br />

operator≪ (StreamType stream, FunctionObjectT func)<br />

{<br />

return output function object(stream, func);<br />

}<br />

By using these objects it is almost possible to offer a convenient way to write the already<br />

presented <strong>for</strong> each - code snippet. The remaining adaptation is to use a so-called unnamed<br />

object instead of the dereferenced iterator arg1.<br />

argument 1 function object arg1;<br />

std::<strong>for</strong> each(vec.begin(), vec.end(), std::cout ≪ arg1);<br />

By creating a collection of functor objects 2 a functional programming style can be mimiced.<br />

As can then be obvserved, polymorphism, which has to be especially provided in the imperative<br />

world, comes naturally to the functional paradigm as no specific assumptions about data types<br />

are required, only conceptual requirements need to be met.<br />

2 Instead of creating all of these functors again, the Boost Phoenix library or the <strong>C++</strong> TR1 lambda library<br />

can be used.

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

Saved successfully!

Ooh no, something went wrong!