How to know whether to use function or delegate

Chris Nicholson-Sauls ibisbasenji at gmail.com
Mon Jul 17 02:40:10 PDT 2006


Reiner Pope wrote:
> When making a program with a callback, how do you decide whether to use 
> a function or a delegate? E.g,
> 
>   void foo(void function(int) consume)
>   { ... }
> 
> or
> 
>   void foo(void delegate(int) consume)
>   { ... }

I would say, when in doubt, go with delegate.  Why?  Consider usage examples of your 
foo()'s signature:

Example #1 - Using it with an established delegate, say bar() of some instance:
# foo(&obj.bar);

Simple!  If you made it a function pointer, then (as far as I know) using member functions 
and nested functions (which would be done the same way as above, just without 'obj') 
ceases to be possible at all.  (If there is a hack or workaround to pass a delegate as a 
function pointer, I want to see that!)


Example #2 - Using an anonymous delegate:
# foo((int a){
#   /*do stuff*/
# });

Concise!  The utility of this should be fairly self-explanatory.


Example #3 - You can still use it with a function, by wrapping it in an anonymous delegate:
# void bar (int a) {
#   /*do stuff*/
# }
#
# foo((int a) {
#   bar(a);
# });

Intuitive?  Maybe not; but still quite straight-forward.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d-learn mailing list