Quantity

A quantity consisting of a value and an associated unit of measurement.

The unary plus, unary minus, addition, subtraction, multiplication, division, comparison, increment and decrement operators are forwarded to the underlying value type, if the operation is meaningful for the given unit(s).

A quantity is only implicitly convertible to the underlying value type (via alias this) if it is dimensionless – divide a quantity by its unit if you want to access the raw value.

  1. struct Quantity(Unit, ValueType = double)
  2. template Quantity(alias unit, ValueType = double)
    @safe
    template Quantity (
    alias unit
    ValueType = double
    ) if (
    isUnitInstance!unit
    ) {}

Examples

1 enum f1 = 6 * foo;
2 static assert(+f1 == f1);
3 static assert(-f1 == (-6) * foo);
4 static assert(-f1 == -(6 * foo));
5 static assert(f1 + f1 == 12 * foo);
6 static assert(f1 - f1 == 0 * foo);
7 static assert({ auto f = 2 * foo; f += 3 * foo; f -= 2 * foo; return f; }() == 3 * foo);
8 static assert(f1 * 2 == 12 * foo);
9 static assert(f1 / 3 == 2 * foo);
10 static assert(2 * f1 == 12 * foo);
11 static assert(12 / f1 == 2 * foo);
12 static assert({ auto f = 2 * foo; f *= 12; f /= 3; return f; }() == 8 * foo);
13 
14 enum f2 = 2 * foo;
15 static assert(f1 * f2 == 12 * foo.pow!2);
16 enum b = 2 * bar;
17 static assert(f1 / b == 3 * foo / bar);
18 static assert(foo / 2 == 0 * foo);
19 static assert(foo / (2 * bar) == 0 * foo / bar);
20 
21 static assert(f1 == 6u * foo);
22 static assert(f1 != f2);
23 static assert(f1 > f2);
24 static assert(!__traits(compiles, f1 != b));
25 static assert(!__traits(compiles, f1 < b));
26 
27 static assert((f1 / b).toString() == "3 bar^(-1) foo");
28 static assert((f1 / b).toString(UnitString.symbol) == "3 br^(-1) f");
29 
30 enum int fromDimless = f1 / foo;
31 
32 // Increment/decrement should only work for dimensionless Quantities.
33 auto f3 = 1 * foo;
34 static assert(!__traits(compiles, ++f3));
35 static assert(!__traits(compiles, --f3));
36 static assert({ auto b = 1 * dimensionless; ++b; return b; }() == 2 * dimensionless);
37 
38 // Implicit conversion in assignments.
39 Quantity!(foo, float) k = 5 * foo;
40 k = 3 * foo;
41 static assert(cast(Quantity!(foo, int))(2.1 * foo) == 2 * foo);
42 
43 // Quantities of affine units.
44 enum fooa = foo.affine!(10, "afoo", "af");
45 enum fa1 = 3 * fooa;
46 static assert(!__traits(compiles, fa1 + fa1));
47 static assert(fa1 + f1 == 9 * fooa);
48 static assert(f1 + fa1 == 9 * fooa);
49 static assert(fa1 - fa1 == 0 * foo);
50 static assert(fa1 - f1 == (-3) * fooa);
51 auto fa2 = 2 * fooa;
52 static assert(!__traits(compiles, fa2 += fa1));
53 static assert(!__traits(compiles, fa2 -= fa1));
54 static assert({ auto fa = 2 * fooa; fa += 3 * foo; fa -= 2 * foo; return fa; }() == 3 * fooa);
55 static assert(fa1.convert!foo == 13 * foo);

Meta