Unexpectedly nice case of auto return type
Basile B.
b2.temp at gmx.com
Tue Dec 3 10:03:22 UTC 2019
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.
More information about the Digitalmars-d-learn
mailing list