Overview of mp-units
mastermp-units
mp-units is a Modern C++ (C++20 and later) library that provides compile-time safety for domain-specific quantities and units. It is built on the ISO 80000 International System of Quantities (ISQ) and is a candidate for C++29 standardization.
Key Safety Features
- Quantity Kind Safety: Distinguishes between quantities that share the same dimension but represent different physical concepts (e.g., frequency
Hzvs. radioactive activityBq). - ISO 80000 (ISQ) Support: Allows functions to require specific quantities (e.g.,
isq::height) rather than generic dimensions (e.g.,isq::length). - Strongly-Typed Numerics: Can be used for non-physics domains like item counts, financial values, or identifiers to prevent accidental mixing of numeric types.
Performance and Integration
- Zero Runtime Overhead: All dimensional analysis is performed at compile time.
- Low Adoption Cost: No external dependencies, macro-free API, C++20 modules-ready, and freestanding-capable.
#include <mp-units/systems/isq.h>
#include <mp-units/systems/si.h>
using namespace mp_units;
using namespace mp_units::si::unit_symbols;
// Compile-time dimensional analysis — zero runtime overhead
static_assert(1 * km / (1 * s) == 1000 * m / s);
// Function signatures encode domain/physics, not just dimensions
void calculate_trajectory(quantity<isq::kinetic_energy[J]> e);
int main()
{
quantity<isq::potential_energy[J]> Ep = 42 * J;
quantity<isq::kinetic_energy[J]> Ek = 123 * J;
calculate_trajectory(Ek); // ✅ correct
// calculate_trajectory(Ep); // ❌ potential energy ≠ kinetic energy (both in J)
// quantity<Gy> q = 42 * Sv; // ❌ absorbed dose ≠ dose equivalent (both J/kg)
}