r/cpp • u/mateusz_pusz • 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.
View all comments
Show parent comment
12
u/wyrn Apr 08 '26
The bigger problem in this case is that it's thoroughly inappropriate for a units library to handle this sort of check. It's one thing to say that an azimuth has to be between 0 and 2pi because that's the convention you're using and other values are degenerate, or to enforce that a probability has to be 0 and 1 -- in other words, to enforce checks that prevent the system from getting into a logically inconsistent state. It's quite another for the scheme to be applied as a clumsy anomaly detector, discarding signals that are valid but unanticipated, or that may be valuable as diagnostic aids. This is essentially a (much more difficult) statistics/machine learning problem, and it deserves a central role in the overall system design if one wants to account for it at all.
E.g. some predict the vacuum energy density is around 1076 (GeV)4 . The measured value is 2.5×10−47 (GeV)4 . That's comically wrong, by about 10120 orders of magnitude, and it for sure means someone screwed up the calculation somewhere. But it doesn't mean it's not a valid value in (GeV)4 .
I like what this library is doing and what it stands for, but I'd caution against overzealous generalizations of the idea of "unit".