New syntax proposal for template type parameter contraints
Idan Arye via Digitalmars-d
digitalmars-d at puremagic.com
Fri May 16 16:14:11 PDT 2014
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. Another problem is that we now have to have an argument
if we want to pass a template parameter, which is a serious
limitation.
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.
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.
BTW - I'm don't think we need a new keyword for this - we can use
`interface template` instead.
More information about the Digitalmars-d
mailing list