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.

210 CHAPTER 7. EFFECTIVE PROGRAMMING: THE POLYMORPHIC WAY<br />

7.4.1 Lambda Calculus<br />

As was presented in Section ref(), is not very easy to reuse the STL standard function objects<br />

because the use is not very intuitive. Either a function object <strong>for</strong> each loop or binder has to be<br />

written. A binder (or binder object) is passed at construction time, to another function object<br />

which per<strong>for</strong>ms an action. The binder takes the function object as well as another binding value<br />

and makes a binary function unary by fixing the first parameter. However it is not obvious at<br />

first. An easy way to implemented such a functionality is to write it as it is:<br />

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

Of course this can not compile <strong>for</strong> several reasons. First the third argument is not a function<br />

object. Second the variable vec iter does not exist, nor does it know anything about the<br />

iterated container vec. Anyway, an expression like this is easy to write and less error prone<br />

compared to a binder object. To enable a program like this the following has to be accomplised:<br />

First the output-stream operator <br />

ArgumentT<br />

operator()(ArgumentT arg)<br />

{<br />

return arg1;<br />

}<br />

template< typename Argument1T, typename Argument2T><br />

ArgumentT<br />

operator()(Argument1T arg1, Argument2T arg2)<br />

{<br />

return arg1;<br />

}<br />

};<br />

So what does this object really do? It provides unary and binary bracket operators <strong>for</strong> one and<br />

two objects which return the argument passed. A function object is implemented next which<br />

stores an arbitrary stream type.<br />

template<br />

output function object<br />

{<br />

output function object (StreamType stream, FunctionObjectT func) : stream(stream), func(func) {}<br />

template < typename ArgumentT><br />

void operator()(ArgumentT arg)<br />

{

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

Saved successfully!

Ooh no, something went wrong!