Constrained Templates
Ali Çehreli
acehreli at yahoo.com
Sun Jun 13 16:05:11 PDT 2010
Leandro Lucarella wrote:
> Walter Bright, el 13 de junio a las 12:01 me escribiste:
>> http://www.drdobbs.com/blog/archives/2010/06/constrained_tem.html
>>
>> Anyone want to do the honors and post to reddit, ycombinator, etc. ?
>
> Nice article, but when I read:
>
> T gcd(T)(T a, T b)
> if (is(typeof(a % b)))
> {
> ...
> }
>
> Under the presence of such beauty as template constraint syntax is,
> "is(typeof(a % b))" makes my eyes hurt, and my brain wonder.
The method that I learned from Phobos is not the best, but at least the
function interface reads better:
T gcd(T)(T a, T b)
if (supports_modulus!T)
{
T result;
// ...
return result;
}
That makes it clear that T must support the modulus operation.
Here is how supports_modulus may be defined:
template supports_modulus(T)
{
const bool supports_modulus = is (typeof(
{
T a;
T b;
T c = a % b;
}()));
}
Here are what is at play to get that "named constraint":
- The curly braces after the typeof define a closure (delegate?) literal
- The body includes how the type should be used to satisfy the
'supports_modulus' constraint
- The closure is "executed" with the empty parethesis at the end of it
(actually, not executed at all; because the expression is a parameter to
typeof, which never executes its argument)
- [This is my assumption] typeof produces an invalid type for invalid
expressions
- One of the uses of the 'is' expression produces a bool result if the
type that it receives is not valid
- When a template contains just one definition and that definition
matches the name of the template, the template instantiation is the same
as the definition that it contains. i.e. instead of writing
(supports_modulus!T).supports_modulus
to mean the bool value, one merely writes
supports_modulus!T
A lot of D features! :) But once that code structure is accepted as an
idiom, it works and gives names to constraints.
Ali
More information about the Digitalmars-d
mailing list