View source code
Display the source code in std/checkedint.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.checkedint.Checked.opCmp

Compares this against rhs for ordering. If Hook defines hookOpCmp, the function forwards to hook.hookOpCmp(get, rhs). Otherwise, the result of the built-in comparison operation is returned.

auto opCmp(U, _) (
  const U rhs
)
if (isIntegral!U || isFloatingPoint!U || is(U == bool));

auto opCmp(U, Hook1, _) (
  Checked!(U,Hook1) rhs
);

If U is also an instance of Checked, both hooks (left- and right-hand side) are introspected for the method hookOpCmp. If both define it, priority is given to the left-hand side.

Parameters

NameDescription
rhs The right-hand side operand
U either the type of rhs or the underlying type if rhs is a Checked instance
Hook1 If rhs is a Checked instance, Hook1 represents the instance's behavior hook

Returns

The result of hookOpCmp if hook defines hookOpCmp. If U is an instance of Checked and hook does not define hookOpCmp, result of rhs.hook.hookOpCmp is returned. If none of the instances specify the behavior via hookOpCmp, -1 is returned if lhs is lesser than rhs, 1 if lhs is greater than rhs and 0 on equality.

Example

import std.traits : isUnsigned;

static struct MyHook
{
    static bool thereWereErrors;
    static int hookOpCmp(L, R)(L lhs, R rhs)
    {
        static if (isUnsigned!L && !isUnsigned!R)
        {
            if (rhs < 0 && rhs >= lhs)
                thereWereErrors = true;
        }
        else static if (isUnsigned!R && !isUnsigned!L)
        {
            if (lhs < 0 && lhs >= rhs)
                thereWereErrors = true;
        }
        // Preserve built-in behavior.
        return lhs < rhs ? -1 : lhs > rhs;
    }
}
auto a = checked!MyHook(-42);
assert(a > uint(42));
assert(MyHook.thereWereErrors);
static struct MyHook2
{
    static int hookOpCmp(L, R)(L lhs, R rhs)
    {
        // Default behavior
        return lhs < rhs ? -1 : lhs > rhs;
    }
}
MyHook.thereWereErrors = false;
assert(Checked!(uint, MyHook2)(uint(-42)) <= a);
//assert(Checked!(uint, MyHook2)(uint(-42)) >= a);
// Hook on left hand side takes precedence, so no errors
assert(!MyHook.thereWereErrors);
assert(a <= Checked!(uint, MyHook2)(uint(-42)));
assert(MyHook.thereWereErrors);

Authors

License