Last update September 15, 2006

Daniel Keep /
Is It AFunction Or ADelegate



Is it a Function or a Delegate?

One problem I encountered when working with D and functional programming was that there were times I would pass a pointer to (what I assumed) was a function, and instead it would pass a delegate.

Eventually, I got sick of guessing what was going on, so I went off and tested every kind of procedure I could think of in order to work out just what is a function, and what is a delegate.

Quick Summary

Below is a quick summary of the results.

If we define func as:

void func() {}

Then what is &func (based on where it was defined)?

  • Function Pointer:
    • Module level
    • Static class or struct method
  • Delegate:
    • Inner function (function in a function)
    • Non-static class or struct method

The Code!

Below is the code I used to test this, so you can try it for yourself.

import std.cstream;

class test_class
{
    public void testfunc_object() {}
    public static void testfunc_class() {}
}

struct test_struct
{
    public static void testfunc_struct() {}
}

void testfunc_module() {}

void showType(void function() f)
{
    dout.writeLine("f is a function");
}
void showType(void delegate() f)
{
    dout.writeLine("f is a delegate");
}

int main()
{
    void testfunc_func() {}
    test_class test_object = new test_class();

    showType(&testfunc_module);
    showType(&testfunc_func);
    showType(&test_object.testfunc_object);
    showType(&test_class.testfunc_class);
    showType(&test_struct.testfunc_struct);
    showType(function(){});
    showType(delegate(){});
    showType({});
    
    return 0;
}

Postscript

If you happen to find any errors in this, feel free to let me know so I can fix it—don't want to look like an idiot, now do I? :P


FolderExamples


FrontPage | News | TestPage | MessageBoard | Search | Contributors | Folders | Index | Help | Preferences | Edit

Edit text of this page (date of last change: September 15, 2006 11:03 (diff))