D - Unsafe and doomed

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Jan 4 14:08:42 PST 2014


On 1/4/14, Adam D. Ruppe <destructionator at 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");
    }
}
-----


More information about the Digitalmars-d mailing list