New syntax proposal for template type parameter contraints
Phil Lavoie via Digitalmars-d
digitalmars-d at puremagic.com
Fri May 16 17:42:34 PDT 2014
On Friday, 16 May 2014 at 23:14:13 UTC, Idan Arye wrote:
> On Friday, 16 May 2014 at 20:31:40 UTC, Phil Lavoie wrote:
>> The idea is to eventually be able to do something like this:
>>
>> constraint InputRange(Elt) {
>> Elt front();
>> void popFront();
>> bool empty();
>> }
>>
>> void myTemplateFunction( InputRange!int r ) {
>> foreach( elt; r ) { ... }
>> }
>>
>> What do you think? Does this feel right to you?
>>
>> Phil
>
> The main problem is that `myTemplateFunction`'s signature makes
> it look like it's a concrete function, when in fact it's a
> template.
True. To me that is not a big issue though. It can lead to some
surprises I see your point but I would be ok with that.
> Another problem is that we now have to have an argument if we
> want to pass a template parameter, which is a serious
> limitation.
Not sure I get what you mean. I didn't mean for the old syntax to
be abandonned if that makes sense, just to add some sugar to the
existing one.
>
> 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) { ... }
}
?
>
> Also it could be nice if a template can implement a constraint
> like classes implement interfaces. Unlike classes&interfaces,
> it shouldn't be a requirement that a template implements a
> constraint in order for it to be used as parameter where the
> constraint is expected. Rather, the compiler should check that
> the template fulfills the constraint even if the template is
> never instantiated(is this possible?). This could be a nice
> mechanism for verifying templates.
>
Hmm do you mean like a struct "implementing" an interface?
struct MagicRange: InputRange {
...
}
Where it's not an actual interface but the compiler would check
it against the constraint(s). Which would be nice to make sure
that a type follows a given interface, although, as soon as it is
used as an InputRange you would know.
>
>
> BTW - I'm don't think we need a new keyword for this - we can
> use `interface template` instead.
Love it! Would "template interface" make more sense?
More information about the Digitalmars-d
mailing list