Templates class member functions not conditional?

monarch_dodra monarchdodra at gmail.com
Tue Sep 11 07:11:09 PDT 2012


On Tuesday, 11 September 2012 at 13:33:08 UTC, bearophile wrote:
> monarch_dodra:
>
>> and forces the implementer to think about the required 
>> conditions to use the function,
>
> I think this is usually considered a good practice in D, just 
> like using template constraints.
>
> If you look in Phobos, similar situations are handled with 
> static ifs. As example see the several static if used inside 
> MapResult() to disable some of its features:
>
> [SNIP]
>
> Bye,
> bearophile

I'd argue it's horrible! Why should the coder bother making these 
conditional, if calling them would have failed anyways?

The fact that it is done like this in D, I'd argue, is by 
necessity, not necessarily by good practice.

IMO, being able to do this is a much better alternative:

     @property auto save()
     {
         static assert(isForwardRange!R); //Optional
         auto result = this;
         result._input = result._input.save;
         return result;
     }

It is cleaner and easier on the developer. The exact line that 
fails is reported (as opposed to "member not found"). An optional 
static assert can make the reason *why* it failed be bloody 
explicit.

The last reason why this approach is superior, is because above, 
"front(T)" *does* exist, but it is implemented as "can't work", 
and calling it MUST fail. This is different from not having it 
implemented, which allows a third party to define it via UFCS. In 
that case though, it would not be enriching the interface, it 
would be hijacking it.


More information about the Digitalmars-d-learn mailing list