Re: Best practices? Free functions vs function objects
Rune Allnor wrote:
In this case one uses a function object which preserves internal
state after having returned the main result.
Ahem, I wouldn't be too sure about that. At least as far as the algorithms
coming from the STL are concerned, I think those take the functor by value,
so the internal state is not available to the caller.
But apart from that? Any other reasons to (not) use a function
object instead of a free function?
The main functional reason for me to use a function object is to pass in
(not out) parameters. This allows e.g. a predicate for std::find() to take
additional parameters. Of course, the same can often be achieved using
bind() and similar things, but the syntax becomes a bit unwieldy at times.
Just compare these two snippets:
it = std::find( clients.begin(), clients.end(),
pred_name("foo"));
it = std::find( clients.begin(), clients.end(),
std::bind_1st( &compare_name, "foo"));
Disclaimer: I'm not actually sure about the syntax of the second. Further,
notice that the type 'pred_name' can actually have an overloaded function
call operator to allow its use to search different element types.
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]