aslike 0.2.0

Duck-typing with check interface


To use this package, run the following command in your project's root directory:

Manual usage
Put the following dependency into your project's dependences section:

ASLIKE

struct Like(T) if (is(T == interface)) -- wrap structure for T, it have methods and private delegate fields matches all methods from T.

Like!T as(T, bool nullCheck=true, X)(auto ref X obj) if (is(T == interface)) -- wrapper method, wrap object X obj into Like!T if it possible (fill all delegate fields in returned Like!T with methods pointers from obj). If X is class or interface and if nullCheck is true enforce obj is not null.

It can be helpful if you want to declare function or method what must get some object as argument, and it object must contains all methods what you want, and if you don't want use classic OOP and/or want use structs.

You can use templates for this, but you can't override class methods at this case, and templace can be less readable what using interface type.

struct wrap example

Or if you want cache virtual methods table lookup for improving performance.

cache wrap example

Using

  1. define interface

    interface Foo
    {
        void func1();
        int func2(int a, int b);
    }
    
  2. use Like!Foo as argument type

    int bar(Like!Foo obj, int a, int b)
    {
        obj.func1();
        return obj.func2(a, b);
    }
    
  3. wrap object by as function

    struct SFoo
    {
        int field;
        void func1() { field++; }
        int func2(int a, int b) { return a + b / field; }
    }
    
    auto x = SFoo(10);
    writeln(bar(x.as!Foo, 15, 20));
    

Notes

Like struct have reference symantics respect to wrapped object.

Be careful when wrap objects allocated on stack: when program exit from scope, reference to object saved in delegates will be broken.

Authors:
  • deviator
Dependencies:
none
Versions:
0.4.0 2020-Dec-12
0.3.0 2020-Aug-12
0.2.0 2020-Aug-12
0.1.1 2020-Jul-11
0.1.0 2020-Jul-11
Show all 6 versions
Download Stats:
  • 0 downloads today

  • 0 downloads this week

  • 0 downloads this month

  • 24 downloads total

Score:
0.7
Short URL:
aslike.dub.pm