Metaprogramming in D : Some Real-world Examples
grauzone
none at example.net
Wed Nov 11 08:58:53 PST 2009
Andrei Alexandrescu wrote:
> grauzone wrote:
>> Don wrote:
>>> Christopher Wright wrote:
>>>> grauzone wrote:
>>>>> You're not testing for types, you're testing if it compiles. Inside
>>>>> the tested block of code, all sorts of things could go wrong. You
>>>>> can't know if is(typeof(...)) really did what you wanted, or if
>>>>> something broke.
>>>
>>> You're testing, "is everything inside that OK?". If you want to know
>>> WHY it's wrong, you'd better make sure you're testing something simple.
>>
>> Andrei's range lib uses it more in a way "does this type support this
>> and that range interface?". Example:
>> http://dsource.org/projects/phobos/browser/trunk/phobos/std/range.d#L58
>
> Then different isXxxRange are used by higher-order ranges in defining
> refined interfaces depending on the interfaces offered by their inputs.
That means if one isXxxRange fails because the user maybe made a typo in
the needed range function, the code will silently do something else.
But my main problem is that the user just gets a "does not match
template declaration" compiler error when he messes up his range
interface. He's neither told that e.g. his range-related function
returns the wrong type, nor is there any other refined error message.
Now what if we'd introduce some sort of interfaces for type checking at
compile time?
interface InputRange(T) {
void popFront();
bool empty();
T front();
}
struct MyRange : InputRange!(int) {
void popFront() { ... }
//compiler error goes here...
void empty() { ... }
int front() { ... }
}
(or something like this)
PS: there are two aspects to the problem: 1. even compile time duck
typing shares some of the problems of runtime duck typing, and 2.
utterly unhelpful error messages. If you wouldn't explicitly check the
interface with is(typeof()), the compiler's error messages would be even
worse because of 1.
> I fail to see how that's terrible. I am very happy D has that feature -
> no other statically-typed language has it, and it can be used to great
> effect. Look e.g. at Chain:
>
> http://dsource.org/projects/phobos/browser/trunk/phobos/std/range.d#L799
>
> There, the uses of static if (is(...)) allow Chain to define as capable
> an interface as its inputs allow.
>
>
> Andrei
More information about the Digitalmars-d-announce
mailing list