i see the use of pointers, from K&R2 but what is the use of:
[snip]
2. pointer to function:
int (*fp) (char*);
These are useful for callbacks, generic programming (e.g. with
std::for_each), etc. See also "functors".
Noooooooooo! This is a function pointer. Functors are related to
objects as in:
class A {
int stateVar;
public: int operator()(int x, int y);
};
That is a functor, it allows an object to act like a function, and
since it has it's own state, it could be used in place of this model
of a function:
mlimber didn't say "This is a function pointer", s/he said "See also
functors" - but didn't say why! Perhaps there's a point to be made along
the lines that functors are frequently used in C++ to provide more elegant
solutions to callbacks, generic programming, etc. than can be achieved
with function pointers, or to "wrap" function pointers to hide ugly
implementation details or provide generic interfaces.
Just my tuppence worth.
[snip]
Sorry but he did, although it wasn't intentional.
These are useful for callbacks, generic programming (e.g. with
std::for_each), etc. See also "functors".
Well, I found it unclear. The comma between "callback" and "generic
programming" is clearly an implied conjunction with the parenthesis
showing an example on how it can be used. I don't see what the etc
was referring to either. "These are useful for callbacks, generic
programming, "... and what? Are there other reasons to use a function
pointer? If I misunderstood the sentence, it was because it was just
poorly formed and was hard to read.
Oh, and although functors are perhaps a more 'elegant' way of
representing a function pointer, it is actually not a function
pointer. It is an object with a function *like* interface and is why
it is called a functor not a function pointer.
I personally find that they are mostly (though not entirely) a waste
of time, as it decouples the code a bit too much (in the case of a
loop, its body can be very far away from the loop which may be a one
shot deal), can be hard to read (because of the decoupling), can add
additional overhead (an additional object is created), adds a lot of
extra typing (a real pain when doing one shot loops), and they can
take some time to get your head around (using the algorithms, not the
functors). Additionally the operator()() syntax is not exactly pretty
either.
On the plus side, it is real neat cool stuff (impress your friends),
and if you use the functors more than 1 or 2 times, then it is a real
gain as you don't copy code your algorithm and its decoupled portion
(the true and only benefit that I see).
Adrian