On Wednesday, 29 May 2013 at 04:15:52 UTC, Walter Bright wrote:
On 5/28/2013 7:40 PM, Jesse Phillips wrote:
On Monday, 27 May 2013 at 07:53:05 UTC, Walter Bright wrote:
In D, right now (and especially with the beta) you can use the NotNull template.

Where is this NotNull template? If it was in Phobos I would expect
http://dlang.org/phobos/std_typecons.html

It's not in Phobos yet:

struct NotNull(T) {
    T p;

    alias p this;

    this(T p) {
        assert(p != null, "pointer is null");
        this.p = p;
    }

    @disable this();

    NotNull opAssign(T p) {
        assert(p != null, "assigning null to NotNull");
        this.p = p;
        return this;
    }
}

Doing this would help move some of that to compile time:

struct NotNull(T) {
    T ptr;

    alias ptr this;

    this(U : T)(U p) {
        assert(p !is null, "pointer is null");
        this.ptr = p;
    }
    this(U : typeof(null))(U p) {
                static assert(false, "pointer is null");
    }

    NotNull opAssign(U : T)(U p) {
        assert(p !is null, "assigning null to NotNull");
        this.ptr = p;
        return this;
    }
    NotNull opAssign(U : typeof(null))(U p) {
                static assert(false, "assigning null to NotNull");
    }
}

Although I think it would be better still if it didn't automatically convert from T as that removes half the benefit of a statically checked NotNull.

One thing you could do is overload the OR operator for "T || NotNull!T" as it is perfectly safe to construct a NotNull!T from that. Plus with shortcut evaluation there is no performance cost.

As a last resort there should be a runtime check available such as assertNotNull(T) which does the conversion.

Reply via email to