Lambda question (deferring evaluation)

Hi, would it be possible to implement something the following lines using lambda, without having all values referring to the same shared object: ... #include <boost/shared_ptr.hpp> #include <boost/lambda/lambda.hpp> #include <algorithm> #include "Foo.h" ... using namespace boost; using namespace boost::lambda; std::vector<shared_ptr<Foo> > foos(10); std::for_each(foos.begin(), foos.end(), _1 = shared_ptr<Foo>(new Foo)); Thanks // Johan

Johan Nilsson wrote: [...]
std::vector<shared_ptr<Foo> > foos(10); std::for_each(foos.begin(), foos.end(), _1 = shared_ptr<Foo>(new Foo));
Lambda way (according to the docs, I haven't tried it): std::for_each( foos.begin(), foos.end(), _1 = bind( constructor< shared_ptr<Foo> >(), new_ptr<Foo>() ) ); (probably leaks when new throws) Old school way: shared_ptr<Foo> createFoo() { return shared_ptr<Foo>( new Foo ); } std::generate( foos.begin(), foos.end(), createFoo );

"Peter Dimov" <pdimov@mmltd.net> wrote in message news:006101c51ff2$f5868e30$6501a8c0@pdimov2...
Johan Nilsson wrote:
[...]
std::vector<shared_ptr<Foo> > foos(10); std::for_each(foos.begin(), foos.end(), _1 = shared_ptr<Foo>(new Foo));
Lambda way (according to the docs, I haven't tried it):
std::for_each( foos.begin(), foos.end(), _1 = bind( constructor< shared_ptr<Foo> >(), new_ptr<Foo>() ) );
I searched the docs but obviously missed/skipped that part ... embarrassing.
(probably leaks when new throws)
Old school way:
shared_ptr<Foo> createFoo() { return shared_ptr<Foo>( new Foo ); }
std::generate( foos.begin(), foos.end(), createFoo );
Cleaner, nicer (but one of my intentions was to finally get around to learn how to use BLL). Thanks // Johan

"Peter Dimov" <pdimov@mmltd.net> wrote in message news:006101c51ff2$f5868e30$6501a8c0@pdimov2...
Johan Nilsson wrote:
[...]
std::vector<shared_ptr<Foo> > foos(10); std::for_each(foos.begin(), foos.end(), _1 = shared_ptr<Foo>(new Foo));
Lambda way (according to the docs, I haven't tried it):
std::for_each( foos.begin(), foos.end(), _1 = bind( constructor< shared_ptr<Foo> >(), new_ptr<Foo>() ) );
(probably leaks when new throws)
Old school way:
shared_ptr<Foo> createFoo() { return shared_ptr<Foo>( new Foo ); }
std::generate( foos.begin(), foos.end(), createFoo );
here is also BOOST_FOREACH way: BOOST_FOREACH( shared_ptr<Foo>&, elem, foos ) elem.reset( new Foo ); Gennadiy

Taking into account "Lambda expressions in details"->"Construction and destruction" docs, perhaps this way: std::for_each(foos.begin(), foos.end(), _1 = bind(constructor<shared_ptr<Foo> >(),bind(new_ptr<Foo>())) ); Didn't try to compile, only guess :)
participants (4)
-
Gennadiy Rozental
-
Johan Nilsson
-
Peter Dimov
-
Roman