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

Chad J chadjoan at __spam.is.bad__gmail.com
Sat Jul 28 14:48:21 PDT 2012


On 07/28/2012 04:55 PM, Jonathan M Davis wrote:
> On Saturday, July 28, 2012 16:47:01 Chad J wrote:
>> "range kind" is informal language.  Maybe I mean "template instances",
>> but that would somewhat miss the point.
>>
>> I don't know how to do this right now.  AFAIK, it's not doable.
>> When I speak of ranges I refer specifically to the std.phobos ranges.
>> There is no Range type right now, but there are the isInputRange,
>> isOutputRange, isForwardRange, etc. templates that define what a Range
>> is.  The problem is that I have no idea how to write something like this:
>>
>> isInputRange!___ r2 = [1,2,3].some.complex.expression();
>>
>> It doesn't make sense.  isInputRange!() isn't a type, so how do I
>> constrain what type is returned from some arbitrary expression?
>
> Well, if you want a check, then just use static assert.
>
> auto r2 = [1,2,3].some.complex.expression();
> static assert(isInputRange!(typeof(r2)));
>
> The result isn't going to magically become something else just because you
> want it to, so all that makes sense is specifically checking that its type is
> what you want, and static assert will do that just fine.
>
> This is completely different from template constraints where the constraint can
> be used to overload functions and generate results of different types depending
> on what's passed in. With the code above, it's far too late to change any
> types by the time r2 is created.
>
> - Jonathan M Davis

I suppose that works, but it isn't very consistent with how type safety 
is normally done.  Also it's extremely verbose.  I'd need a lot of 
convincing to chose a language that makes me write stuff like this:

auto foo = someFunc();
static assert(isInteger!(typeof(foo));

instead of:

int foo = someFunc();

I can tolerate this in D because of the obvious difference in power 
between D's metaprogramming and other's, but it still seems very 
lackluster compared to what we could have.


More information about the Digitalmars-d-learn mailing list