"static interface" for structs

Gor Gyolchanyan gor.f.gyolchanyan at gmail.com
Tue Oct 11 07:21:05 PDT 2011


Right. It is far too verbose, but those protocols are too restrictive.
With no run-time value, the protocols must be very flexible to contain
any kind of requirements on structs, that are practically useful to
have.
The __traits(compiles, ...) would be awesome to be automatically be
used in templates:

void func(Type)(Type param)
{
    Type temp = new Type;
    temp.method(param);
}

This code requires the Type to be either a class or a struct with a
this(typeof(this)*) { } implemented in it.
If the test for it was automatically included in the template's
constraint, it would make templates so much easier to use.
Templates would then overload on their bodies. You'd just write
several implementations of the template and the correct one would be
automatically chosen, based on the implementation itself.
And in case none of them are applicable, the compiler would be able to
tell you exactly what does your template parameter lack.
But we don't have that, unfortunately.

On Tue, Oct 11, 2011 at 6:01 PM, Andrej Mitrovic
<andrej.mitrovich at gmail.com> wrote:
> On 10/11/11, Gor Gyolchanyan <gor.f.gyolchanyan at gmail.com> wrote:
>> Actually, the __traits(compiles, ...) is a marvelous and very powerful
>> tool that will allow you to test if the struct is fit for your
>> particular task by just specifying the task.
>
> Yeah, but you have to write very specific code to test if it really is
> a compatible type. And even after all that hard work you could still
> easily pass a type that "walks like a duck" but that you know is
> actually incompatible. So then you have to write specific if(!is(T ==
> IncompatibleType)), and this doesn't scale too well.
>
> This is why I resort to having an enum boolean as the first field of a
> struct that defines its "protocol", but I really see that as a
> poor-man's implementation of interfaces.
>


More information about the Digitalmars-d mailing list