Templatized delegates

Andrey Zherikov andrey.zherikov at gmail.com
Tue May 31 23:15:24 UTC 2022


On Tuesday, 31 May 2022 at 21:53:17 UTC, Paul Backus wrote:
> If you want compile-time polymorphism, three's no other way.

Yes, I want compile-time polymorphism.

> ```d
> import std.stdio;
>
> struct S
> {
>     // function that should be called from delegate
>     void doSomething(T)(T value) { value.writeln; }
> }
>
> interface I
> {
>     void doSomething(int value);
> }
>
> class Adapter : I
> {
>     S s;
>     this(S s) { this.s = s; }
>     void doSomething(int value) { s.doSomething(value); }
> }
>
> alias DG = void delegate (I i);
>
> auto createDG(int value)
> {
>     return delegate (I i) { i.doSomething(value); };
> }
>
> struct R
> {
>     DG dg;
>
>     this(int value)
>     {
>         dg = createDG(value);
>     }
> }
>
> void main()
> {
>     auto r = R(5);
>
>     S s;
>     r.dg(new Adapter(s));
> }
> ```

Unfortunately this solution looses important feature: there is no 
more templated call to `S.doSomething` as `I.doSomething` is not 
template and adding override for every type is not maintainable.


More information about the Digitalmars-d-learn mailing list