Unexpectedly nice case of auto return type

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Dec 3 09:58:36 UTC 2019


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





More information about the Digitalmars-d-learn mailing list