Originally Posted by
pheres
Is there any advantage from bind above defining a normal functor?
well you don't have to write the functor for a start!
I'm not shure if I got it:
for_each(v2.begin(), v2.end(), cout << *_1 << " ");
-> _1 is "used to create objects with operator() defined [...] that it takes one argument and straightly returns that value."
So it takes what? an interator? and returns what? also an interator? what exactly happens in this line?
I doesn't see the differnce to this one:
for_each(v2.begin(), v2.end(), delete _1 );
if *_i in the first line returns a string, than _i is returning a string*. ok that seems perfekt, because delete wants exactly that: an string*.
on what point is my brain going out of order?
ok first up, damn you for asking this, 'cos now I have to think about it and anything lambda/bind related makes my brain hurt!
right, think of it like this.
_1 is not "returning a string*". _1 conceptually looks more like this
Code:
template <class something, class fn, class returntype, class arg1> // returntype and arg1 may not be present, depending on the function
class _1
{
// ctor
_1(something &thing, fn func)
: mything(thing)
, myfunc(func)
{
}
returntype operator()(arg1 arg)
{
return func(mything, arg);
}
private:
something &mything;
fn myfunc;
}
now to say that's a vast oversimplification would be like saying the pacific is a really big lake, but anyway.
when you do your for_each it actually looks like this
Code:
std::list<stuff> slist;
for-each (slist.begin(), slist.end(), cout << _1);
// pseudo-code
for (; begin != end; ++begin)
{
_1<stuff, ostream(*)(ostream &, const stuff&)> // ostream(*)(ostream &, const stuff&) is a function pointer type
lambda_obj(begin, &operator<<(ostream &, const stuff&);
lambda_obj();
}
so you can see that the code never calls lambda_obj.c_str(). when you do
Code:
for_each(v3.begin(), v3.end(), cout << _1->c_str()
the compiler goes "hmmm class _1 doesn't HAVE a c_str method!"
the reason that *_1 works is that _1 actually does overload the * operator. If you're really feeling masochistic you can have a look in boost/lambda/detail/operator_lambda_func_base.hpp and after you've waded through the preprocessor madness you'll see it