New syntax proposal for template type parameter contraints
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Fri May 16 18:53:46 PDT 2014
On Fri, 16 May 2014 20:42:34 -0400, Phil Lavoie <maidenphil at hotmail.com>
wrote:
> On Friday, 16 May 2014 at 23:14:13 UTC, Idan Arye wrote:
>>
>> How about if instead these constraint could be used in `is` expressions
>> like type specializations?
>>
>> void myTemplateFunction(T)(T r) if(is(T : InputRange!int)) {
>> foreach(elt; r) { ... }
>> }
>>
>> True, the syntax is less elegant, but it's more flexible, you can
>> easily tell that it's a template, and you can use the same syntax in
>> static branching.
>>
>
> It's interesting. But would it warrant a change from the usual syntax,
> which would probably be:
>
> void myTemplateFunction(T)(T r) if( isInputRange!(T, int)) {
> foreach(elt; r) { ... }
> }
>
I just want to say, these two do not look very different.
There are a couple things I want to say about these ideas without saying I
agree or disagree with the proposals. These are the problems with the
current system:
1. The template constraint is all or nothing. If you have a complex
if-statement, and one bit fails, it's often difficult to determine what
happened.
2. The template constraint is decoupled from the parameters themselves. If
you have 5 parameters, you have to match the parameters to how they are
constrained, and that isn't always straightforward.
I agree that the original proposal does not look template-ish enough.
I think we can do a lot with the existing trait templates to solve these 2
major problems. A possible solution:
template interface isInputRange(T, E) { .. No change in implementation .. }
void myTemplateFunction(T : isInputRange!int)(T t)
{
}
would basically change this into the equivalent of today's constraints.
however, given that the template parameter is coupled with the constraint
more directly, a better error message could be created, e.g. "Type
MyNonRangeType does not satisfy template interface isInputRange!int."
I'm not sure the above doesn't conflict with current syntax, but I like it
a hell of a lot better than the decoupled constraint afterward.
-Steve
More information about the Digitalmars-d
mailing list