Generic comparison

Paul Backus snarwin at gmail.com
Tue Nov 10 17:09:00 UTC 2020


On Tuesday, 10 November 2020 at 16:55:11 UTC, Ola Fosheim Grøstad 
wrote:
> I want to implement a generic function for "a < f(x) < b" that 
> will give the same result as "(a < f(x)) && (f(x) < b)" for any 
> conceivable mix of types. Except if that "f(x)" should only be 
> evaluated once.
>
> Is it sufficient to use "scope ref" in parameters?
>
> I don't want to assume _anything_ about the definition of the 
> types and the implementation of the comparison operator (can be 
> overloaded).

bool between(Value, Bound)(auto ref Value value, auto ref Bound 
low, auto ref Bound high)
{
     return (low < value) && (value < high);
}

You need `auto ref` because either Bound or Value may have 
copying disabled. Because the function is a template, attributes 
like `scope` will be inferred when applicable (modulo compiler 
bugs).


More information about the Digitalmars-d-learn mailing list