r/cpp • • Apr 07 '26

Range-Validated Quantity Points - mp-units

https://mpusz.github.io/mp-units/latest/blog/2026/04/06/range-validated-quantity-points/

Physical units libraries have always been very good at preventing dimensional errors and unit mismatches. But there is a category of correctness that they have universally ignored: domain constraints on quantity point values.

A latitude is not just a length divided by a radius. It is a value that lives in [-90°, 90°]; anything outside that range is physically meaningless. An angle used in bearing navigation wraps cyclically around a circle; treating it as an unbounded real number ignores a fundamental property of the domain. A clinical body-temperature sensor should reject a reading of 44 °C at the API boundary, not silently pass it downstream.

No units library — before this work — has provided a way to attach this kind of constraint to a quantity point at the type level, have it enforced automatically, and express different flavors (clamp, wrap, reflect, check) without any runtime polymorphism.

This article describes the motivation in depth, the design we arrived at, and the open questions we would love the community's help to answer.

31 Upvotes

7 comments sorted by

View all comments

Show parent comment

1

u/XeroKimo Exception Enthusiast Apr 07 '26

No clue if it's something done much in practice, but are you able to convert units and still have the range constraint follow through the conversion? Taking an example in the post, the body temperature is clamped [35℃, 42℃], could you convert the unit in ℉ or K (for whatever reason), and the range clamps to whatever [35℃, 42℃] is in ℉ or K?