Unexpectedly nice case of auto return type
Basile B.
b2.temp at gmx.com
Tue Dec 3 07:24:31 UTC 2019
On Tuesday, 3 December 2019 at 07:12:18 UTC, Basile B. 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.
Actually I think this can work because of a Tnull (internal
compiler type) inference which can always implictly be converted
to the static return type (A or B, or even int*):
auto alwaysReturnNull()// `auto` is translated to Tnull by
inference because of `return null`
then:
A testA()
{
return alwaysReturnNull(); // Tnull can be implictly
converted to A
}
still nice tho.
More information about the Digitalmars-d-learn
mailing list