You're viewing a comment by Gennaro Prota and its responses.

May 18, 2010, 18:15

The standard just requires a copy of f to be returned. This means that, for instance, the following implementation is perfectly legal:

template< typename InputIterator, typename Function >
Function
for_each( InputIterator first, InputIterator last, Function f )
{
    if ( first != last ) {
        f( *first ) ;
        for_each( first + 1, last, f ) ;
    }
    return f ;
}

This is a typical gotcha for C++ beginners.

(There are also other small oversights in the code, but this is the main one.)

PS: Also, I think that standard-wise the only occurrence of the term "functor" I've seen is in the draft specification for unique_ptr (but I'd have to check if it's still there; if so it ought probably be replaced by "function object"). But of course it's a term in common usage, sometimes referring to classes, sometimes to objects (instances).

Comment Responses

May 19, 2010, 00:04

Oops, I forgot to stick to input iterators, sorry. It should of course be:

template< typename InputIterator, typename Function >
Function
for_each( InputIterator first, InputIterator last, Function f )
{
    if ( first != last ) {
        f( *first ) ;
        ++ first ;
        for_each( first, last, f ) ;
    }
    return f ;
}

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "server_219": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.