D: Delegates or callbacks?

I understood the concept of delegates very well. I really don't understand why I cannot just pass one function to another, and I need to pass it to the delegate. I read in the documents that there are some cases where I do not know his name, and a delegate is only a way to call him.

But now it’s hard for me to understand the concept of callbacks. I tried to find more information, but I can’t understand if it’s just a call to another function or what it is.

Could you show examples of D callbacks and explain where they can be useful?

import vibe.d;

shared static this()
{
    auto settings = new HTTPServerSettings;
    settings.port = 8080;

    listenHTTP(settings, &handleRequest);
}

void handleRequest(HTTPServerRequest req,
                   HTTPServerResponse res)
{
    if (req.path == "/")
        res.writeBody("Hello, World!", "text/plain");
}

&handleRequestis it a callback? How does it work and at what point does it start?

+4
source share
4 answers

, .

void test(){}
void receiver(void function() fn){
    // call it like a normal function with 'fn()'
    // or pass it around, save it, or ignore it
}

// main
receiver(&test); // 'test' will be available as 'fn' in 'receiver'

&, , . , - UFCS ( ). .

, , , . , -. , ( ), listenHTTP, , . : https://en.wikipedia.org/wiki/Event_(computing)#Event_handler

- . , , , . , . :

class BuildGui {

    Indicator indicator;
    Button button;

    this(){
        ... init
        button.clickHandler({ // curly braces: implicit delegate in this case
            indicator.color = "red"; // notice access of BuildGui member
        });
        button.clickHandler(&otherClickHandler); // methods of instances can be delegates too
    }

    void otherClickHandler(){
        writeln("other click handler");
    }

}

Button .

+2

, . , . . RETT function(ARGST) D. RETT - , ARGST - . , .

. (), ( ) , , /.

RETT delegate(ARGST). , .

, , , X, , , X, /.

&handleRequest, , .

+3

OP . :

Q: D , ?

A:. , (# ) . - , . , , . ++ FLTK 2.0: http://www.fltk.org/doc-2.0/html/group__example2.html. , . , , ... FLTK - fltk::Window window_callback, . (, FLTK , , FLTK. ++ lambdas, )

D: http://dlang.org/phobos/std_signals.html

: ?

A: - , ... . , , . , , ( , C/++).

, , , D

1:

2:

, :

struct Foo
{
    int a = 7;
    int bar() { return a; }
}

int foo(int delegate() dg)
{
    return dg() + 1;
}

void test()
{
    int x = 27;
    int abc() { return x; }
    Foo f;
    int i;

    i = foo(&abc);   // i is set to 28
    i = foo(&f.bar); // i is set to 8
}
+2

. .

: .

C , ( ) void * () :

void callback(void *context, ...) {
    /* Do operations with context, which is usually a struct */

    doSomething((struct DATA*)context, ...);
    doSomethingElse((struct DATA*)context, ...);
}

++ , . , void *, () :

void callback(void* object, ...) {
    ((MyObject*)object)->method(...);
}

.

0
source

Source: https://habr.com/ru/post/1612533/


All Articles