Interfaces with structs...?

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 5 11:30:26 PDT 2012


On Thursday, July 05, 2012 20:17:24 Era Scarecrow wrote:
>   Something that was coming to mind a while back was that classes
> can include interfaces while structs cannot. I can understand
> easily why this wouldn't work being much lower level compared to
> how classes are (And the vast varying of parameters and return
> types).
> 
>   But could the notation be allowed for more documentation
> purposes? Or more for contract debugging? Course it would only
> work with templates since that's how the constraints work...
> 
>   Example:
> 
>   struct something : isForwardRange
>   {}
> 
>   I would think the equivalent would be a simple conversion to a
> unittest code:
> 
>   struct something{}
> 
>   unittest {
>    assert(isForwardRange(something), "Fails to satisfy
> 'isForwardRange' template!");
>   }
> 
>   Now this is just a thrown out thought/idea, but curiously I
> don't think it would change much semantically... would it?

Aside from the problem that it looks like inheritance when it's not, declaring 
an interface for a struct would actually be too restrictive in many cases. 
Look at what isForwardRange looks like

template isForwardRange(R)
{
    enum bool isForwardRange = isInputRange!R && is(typeof(
    (inout int _dummy=0)
    {
        R r1 = void;
        R r2 = r1.save; // can call "save" against a range object
    }));
}

If it were defined with an interface, how would you deal with the fact that 
none of the types are fixed? Templatize the interface? That might work, but the 
more complicated the requirements for the template constaint, the harder that 
will be, and I'm not sure that it can even always work to do that. What we 
have may take some getting used to, but it works really well.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list