On Saturday, 7 May 2022 at 02:29:59 UTC, Salih Dincer wrote:
On Friday, 6 May 2022 at 18:04:13 UTC, JG wrote:
```d
//...
struct Adder {
    int a;
    int opCall(int b) { return a+b; }
}
auto adder(int a) {
    auto ret = Adder.init;
    ret.a=a;
    return ret;
}

void main() {
    auto g = adder(5);
    g(5).writeln; // 10
    auto d = toDelegate!(int, int)(g);
    d(5).writeln; // 10
// ...
}
```

The value returned by the delegate structure in the above line is 10. Its parameter is 5, but if you do it to 21, you will get 42. So it doesn't have the ability to delegate Adder.

In summary, the sum function isn't executing. Instead, its value gets double.

SDB@79

What do you mean?

```d
import std;

struct Delegate(A,B) {
    B function(void* ptr, A a) f;
    void* data;
    B opCall(A a) {
        return f(data,a);
    }
}

auto toDelegate(A, B,S)(ref S s) {
    static B f(void* ptr, A a) {
        return (*(cast(S*) ptr))(a);
    }
    Delegate!(A,B) ret;
    ret.f=&f;
    ret.data= cast(void*) &s;
    return ret;
}

struct Adder {
    int a;
    int opCall(int b) { return a+b; }
}
auto adder(int a) {
    auto ret = Adder.init;
    ret.a=a;
    return ret;
}

void main() {
    auto g = adder(5);
    g(5).writeln;
    auto d = toDelegate!(int, int)(g);
    d(41).writeln;
    auto a =7;
    auto h = (int b)=>a+b;
    auto d1 = toDelegate!(int,int)(h);
    void* ptr = cast(void*) &h;
    (*cast(int delegate(int)*) ptr)(10).writeln;
    d1(21).writeln;
    h(32).writeln;
}
```
Output:
10
46
17
28
39

Which is what is expected.


Reply via email to