SafeAccess

Allows to build access chains of class members as done with the ?. operator in other languages. In the chain, any null member that is a class instance or that returns one, has for effect to shortcut the complete evaluation.

This function is copied from https://github.com/BBasile/iz to avoid a new submodule. Any change made to this copy should also be applied to the origin.

struct SafeAccess (
M
) if (
is(M == class)
) {
M m;
}

Disabled Default Constructor

A disabled default is present on this object. To use it, use one of the other constructors or a factory function.

Constructors

this
this(M m)

Instantiate.

Alias This

m

Members

Aliases

unwrap
alias unwrap = m

Unprotect the class instance.

Functions

opDispatch
auto ref opDispatch(auto ref A a)

Handles safe access.

Bugs

Assigning a member only works with unwrap.

Examples

General usage

1 class LongLineOfIdent3{int foo; void setFoo(int v) @safe{foo = v;}}
2 class LongLineOfIdent2{LongLineOfIdent3 longLineOfIdent3;}
3 class LongLineOfIdent1{LongLineOfIdent2 longLineOfIdent2;}
4 class Root {LongLineOfIdent1 longLineOfIdent1;}
5 
6 SafeAccess!Root sar = SafeAccess!Root(new Root);
7 // without the SafeAccess we would receive a SIGSEGV here
8 sar.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3.setFoo(0xDEADBEEF);
9 
10 bool notAccessed = true;
11 // the same with `&&` whould be much longer
12 if (LongLineOfIdent3 a = sar.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3)
13 {
14 	notAccessed = false;
15 }
16 assert(notAccessed);
17 
18 // checks that forwarding actually works
19 sar.m.longLineOfIdent1 = new LongLineOfIdent1;
20 sar.m.longLineOfIdent1.longLineOfIdent2 = new LongLineOfIdent2;
21 sar.m.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3 = new LongLineOfIdent3;
22 
23 sar.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3.setFoo(42);
24 assert(sar.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3.unwrap.foo == 42);

Meta