wrap

Supports structural based typesafe conversion.

If Source has structural conformance with the interface Targets, wrap creates an internal wrapper class which inherits Targets and wraps the src object, then returns it.

unwrap can be used to extract objects which have been wrapped by wrap.

  1. template wrap(Targets...)
  2. template wrap(Targets...)
    template wrap (
    Targets...
    ) if (
    Targets.length >= 1 &&
    !allSatisfy!(isMutable, Targets)
    ) {}
  3. template unwrap(Target)
  4. template unwrap(Target)

Examples

1 interface Quack
2 {
3     int quack();
4     @property int height();
5 }
6 interface Flyer
7 {
8     @property int height();
9 }
10 class Duck : Quack
11 {
12     int quack() { return 1; }
13     @property int height() { return 10; }
14 }
15 class Human
16 {
17     int quack() { return 2; }
18     @property int height() { return 20; }
19 }
20 
21 Duck d1 = new Duck();
22 Human h1 = new Human();
23 
24 interface Refleshable
25 {
26     int reflesh();
27 }
28 
29 // does not have structural conformance
30 static assert(!__traits(compiles, d1.wrap!Refleshable));
31 static assert(!__traits(compiles, h1.wrap!Refleshable));
32 
33 // strict upcast
34 Quack qd = d1.wrap!Quack;
35 assert(qd is d1);
36 assert(qd.quack() == 1);    // calls Duck.quack
37 // strict downcast
38 Duck d2 = qd.unwrap!Duck;
39 assert(d2 is d1);
40 
41 // structural upcast
42 Quack qh = h1.wrap!Quack;
43 assert(qh.quack() == 2);    // calls Human.quack
44 // structural downcast
45 Human h2 = qh.unwrap!Human;
46 assert(h2 is h1);
47 
48 // structural upcast (two steps)
49 Quack qx = h1.wrap!Quack;   // Human -> Quack
50 Flyer fx = qx.wrap!Flyer;   // Quack -> Flyer
51 assert(fx.height == 20);    // calls Human.height
52 // structural downcast (two steps)
53 Quack qy = fx.unwrap!Quack; // Flyer -> Quack
54 Human hy = qy.unwrap!Human; // Quack -> Human
55 assert(hy is h1);
56 // structural downcast (one step)
57 Human hz = fx.unwrap!Human; // Flyer -> Human
58 assert(hz is h1);
1 import std.traits : FunctionAttribute, functionAttributes;
2 interface A { int run(); }
3 interface B { int stop(); @property int status(); }
4 class X
5 {
6     int run() { return 1; }
7     int stop() { return 2; }
8     @property int status() { return 3; }
9 }
10 
11 auto x = new X();
12 auto ab = x.wrap!(A, B);
13 A a = ab;
14 B b = ab;
15 assert(a.run() == 1);
16 assert(b.stop() == 2);
17 assert(b.status == 3);
18 static assert(functionAttributes!(typeof(ab).status) & FunctionAttribute.property);

Meta

Suggestion Box / Bug Report