max() in phobos, and English logic operators

Sean Kelly sean at f4.ca
Wed Nov 8 05:54:32 PST 2006


Jarrett Billingsley wrote:
> "David Qualls" <davidlqualls at yahoo.com> wrote in message 
> news:eirqai$he$1 at digitaldaemon.com...
> 
>> So, is it possible to use templates to define generic binary
>> operators; like 'and' and 'or', or a unary operator like 'not'?
> 
> Not like the way you'd use the iso646 ones.  It'd be really unnatural:
> 
> if(not(and(a, or(b, c))))
>     ...

Yup.  These are in C++ only to allow expressions to be built using 
template composition for use in algorithms.  And the result quickly gets 
annoyingly complex and hard to read.  Lambda expression are a much 
clearer replacement, which we have to some degree with lazy parameters 
and anonymous delegates.  By contrast, C++ uses fancy classes with 
cleverly overloaded operators and some global placeholders.  It works 
fairly well all things considered, but the code behind it is a bit much.

>> After looking at the mass of code it takes to implement a simple
>> generic max() or min() function in D, I'm really starting to pine
>> for my C preprocessor...
>>
>> #define max(a,b) ((a)>(b)?(a):(b))
>>
>> Yeah, I know it breaks if a or b include side effects, but it's
>> extremely READABLE! (And back on my old soap-box, even FORTRAN and
>> Basic include English binary logic operators ;-)
> 
> Well, if you make the max function a bit less generic, restricting it to 
> just one input type, it becomes
> 
> T max(T)(T a, T b)
> {
>     return (a > b) ? a : b;
> }
> 
> Which is pretty readable to me, and probably covers most of the use cases. 
> Most of that conversion stuff in Sean's implementation is probably type 
> trait stuff which would best belong in std.traits (when it comes out).. 

Agreed on both counts.  My template was really to avoid requiring the 
user to explicitly specify template type parameters of the types of a 
and b are different, to make min/max behave as close to the C macro as 
possible.


Sean



More information about the Digitalmars-d-learn mailing list