Differing levels of type-inference: Can D do this?

Jonathan M Davis jmdavisProg at gmx.com
Sat Jul 28 00:03:32 PDT 2012


On Saturday, July 28, 2012 02:49:16 Chad J wrote:
> Is there some way to do something similar to this right now?
> 
> void main()
> {
>    // Differing levels of type-inference:
>    int[]       r1 = [1,2,3]; // No type-inference.

That works just fine.

>    Range!(int) r2 = [1,2,3]; // Only range kind inferred.

What do you mean by range kind? If you declare Range!int, you gave it its type 
already. It's whatever Range!int is. You can't change it. There's nothing to 
infer. Either Range!int has a constructor which takes an int[] or the 
initialization won't work. Range!int is the same either way.

>    Range       r3 = [1,2,3]; // Element type inferred.

Again, the type of the variable must already be a full type, or you can't 
declare it. So, there's nothing to infer. Either Range!int has a constructor 
which takes an int[] or the initialization won't work. Range is the same 
either way.

>    auto        r4 = [1,2,3]; // Full type-inference.

This works;

> AFAIK it isn't: the type system is pretty much all-or-nothing about
> this.  Please show me that I'm wrong.

The _only_ time that the type on the left-hand side of an assignment 
expression depends on the type of the right-hand side is if the type is being 
explicitly inferred by using auto, const, immutable, or enum as the type by 
themselves. Types are never magically altered by what you assign to them.

If you want to, you can create a templated function which picks the type to 
return. e.g.

Type var = makeType([1, 2, 3]);

or

auto var = makeType([1, 2, 3]);

but it's the function which determines what the type is.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list