On 1/4/14, Adam D. Ruppe <destructiona...@gmail.com> wrote: > The big thing people have asked for before is > > Object foo; > if(auto obj = checkNull(foo)) { > obj == NotNull!Object > } else { > // foo is null > } > > and i haven't figured that out yet...
Here you go: ----- import std.stdio; struct NotNull(T) { T obj; } struct CheckNull(T) { private T _payload; auto opCast(X = bool)() { return _payload !is null; } @property NotNull!T getNotNull() { return NotNull!T(_payload); } alias getNotNull this; } CheckNull!T checkNull(T)(T obj) { return CheckNull!T(obj); } class C { } void main() { Object foo; if (auto obj = checkNull(foo)) { writeln("foo is not null"); } else { writeln("foo is null"); } foo = new C; if (auto obj = checkNull(foo)) { // note: ":" rather than "==" due to alias this. static assert(is(typeof(obj) : NotNull!Object)); // assignment will work of course (alias this) NotNull!Object obj2 = obj; writeln("foo is not null"); } else { writeln("foo is null"); } } -----