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/Morwenn Apr 08 '26

Generally speaking, I've seen the pattern than we should separate setpoints and measurements: bounds on setpoints make sense to restrict ranges to what's legal/valid, bounds on measurements mean that you might not be able to register something exceptional you actually witnessed, and that's a problem.

A practical example I encountered IRL was with pesticide dose: you definitely wanna limit recommendations (setpoints) to legal doses, but if a farmer tells you they used X amount on their field, then you absolutely want to register that amount even if it exceeds the legal doses.