Unexpectedly nice case of auto return type

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Dec 3 10:19:02 UTC 2019


On Tuesday, December 3, 2019 3:03:22 AM MST Basile B. via Digitalmars-d-
learn wrote:
> On Tuesday, 3 December 2019 at 09:58:36 UTC, Jonathan M Davis
>
> wrote:
> > On Tuesday, December 3, 2019 12:12:18 AM MST Basile B. via
> >
> > Digitalmars-d- learn wrote:
> >> I wish something like this was possible, until I change the
> >> return type of `alwaysReturnNull` from `void*` to `auto`.
> >>
> >>
> >> ---
> >> class A {}
> >> class B {}
> >>
> >> auto alwaysReturnNull() // void*, don't compile
> >> {
> >>
> >>      writeln();
> >>      return null;
> >>
> >> }
> >>
> >> A testA()
> >> {
> >>
> >>      return alwaysReturnNull();
> >>
> >> }
> >>
> >> B testB()
> >> {
> >>
> >>      return alwaysReturnNull();
> >>
> >> }
> >>
> >> void main()
> >> {
> >>
> >>      assert( testA() is null );
> >>      assert( testB() is null );
> >>
> >> }
> >> ---
> >>
> >> OMG, isn't it nice that this works ?
> >>
> >> I think that this illustrates an non intuitive behavior of auto
> >> return types.
> >> One would rather expect auto to work depending on the inner
> >> return type.
> >
> > The void* version doesn't work, because void* doesn't
> > implicitly convert to a class type. It has nothing to do with
> > null. auto works thanks to the fact that typeof(null) was added
> > to the language a while back, and since class references can be
> > null, typeof(null) implicitly converts to the class type.
> > Before typeof(null) was added to the language, null by itself
> > had no type, since it's just a literal representing the null
> > value for any pointer or class reference. The result was that
> > using null in generic code or with auto could run into issues.
> > typeof(null) was added to solve those problems.
> >
> > - Jonathan M Davis
>
> That's interesting details of D developement. Since you reply to
> the first message I think you have not followed but in the last
> reply I told that maybe we should be able to name the type of
> null. I think this relates to TBottom too a bit.

There isn't much point in giving the type of null an explicit name given
that it doesn't come up very often, and typeof(null) is quite explicit about
what the type is. Also, anyone doing much generic programming in D is going
to be well versed in typeof. They might not know about typeof(null)
explicitly, but they should recognize what it means when they see it, and if
someone were trying to get the type of null, it would be the obvious thing
to try anyway. And typeof(null) isn't even the prime case where typeof gets
used on something other than an object. From what I've seen, typeof(return)
gets used far more.

As for TBottom, while the DIP does give it a relationship to null, they're
still separate things, and giving typeof(null) a name wouldn't affect
TBottom at all.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list