safeOp.unary

Perform the unary (single-argument) integer operation specified by op.

Trying to negate - an unsigned value will generate a compile-time error, because mathematically, the result should always be negative (except for -0), but the unsigned return type cannot represent this.

++ and -- are checked for overflow at runtime, and will raise IntFlag.posOver or IntFlag.negOver if needed.

  1. N unary(const N num)
    template safeOp(IntFlagPolicy policy)
    N
    unary
    @safe
    (
    string op
    N
    )
    (
    const N num
    )
    if (
    (isIntegral!N) &&
    op.among!("-", "+", "~")
    )
  2. N unary(return ref N num)

Examples

1 import checkedint.sticky : safeOp; // use IntFlagPolicy.sticky
2 
3 assert(safeOp.unary!"~"(0u) == uint.max);
4 
5 assert(safeOp.unary!"-"(20L) == -20L);
6 static assert(!__traits(compiles, safeOp.unary!"-"(20uL)));
7 safeOp.unary!"-"(long.min);
8 assert(IntFlags.local.clear() == IntFlag.posOver);
9 
10 auto a = safeOp.unary!"+"(uint.max);
11 static assert(is(typeof(a) == uint));
12 assert(a == uint.max);
13 
14 uint b = 1u;
15 assert(safeOp.unary!"--"(b) == 0u);
16 assert(b == 0u);
17 safeOp.unary!"--"(b);
18 assert(IntFlags.local.clear() == IntFlag.negOver);
19 
20 int c = 7;
21 assert(safeOp.unary!"++"(c) == 8);
22 assert(c == 8);

Meta