Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
U

units

> DevOps
Open source

a compile-time, header-only, dimensional analysis and unit conversion library built on c++14 with no dependencies.

1.1K stars0 likes0 views
WebsiteGitHub

About

a compile-time, header-only, dimensional analysis and unit conversion library built on c++14 with no dependencies.

units

A compile-time, header-only, dimensional-analysis and unit-conversion library for C++23, with no dependencies.

units represents physical quantities as types. A quantity is a value with a unit — meters, feet, seconds — that behaves like the number it wraps. Conversions between compatible units are implicit and resolved at compile time; expressions that are dimensionally inconsistent do not compile.

Quantities are written with unit literals (5.0_m) or by multiplying a value by a unit constant (60.0 * km):

…

cpp #include // everything; or , , ... for a subset using namespace units; using namespace units::literals; // the _m, _s, _kg, ... literals

…

cpp meters a(5.0); // construction (CTAD deduces meters) meters b = 5.0_m; // a unit literal meters c = 5.0 * m; // a value times a unit constant (units::m) meters d{5.0}; // braced construction

…

cpp meters local(5.0); // bare name, deduced meters meters<> m; // default representation meters as_float(5.0f); // explicit representation // void f(meters q); // ill-formed: a parameter has no initializer to deduce from // meters make(); // ill-formed: a return type has no initializer to deduce from


**`auto` vs. an explicit type.** Use `auto` on the left when the right-hand side already states the unit:

```cpp
auto d = 5.0_m;                  // meters
auto speed = 60.0_mi / 1.0_hr;   // a velocity

Write the type explicitly on the left when the compiler should confirm the dimensional analysis: naming the result type makes a mismatch a compile error rather than an accepted auto deduction.

cpp
square_meters     area  = 15.0_m * 5.0_m;    // the result is an area
meters_per_second speed = 100.0_m / 8.0_s;   // the result is a velocity
// meters bad = 15.0_m * 5.0_m;              // ill-formed: the result is an area, not a length

Convert by assigning between compatible units (implicit, and only when lossless):

cpp
meters m = 100.0_ft;    // feet -> meters
feet   f = m;           // meters -> feet

Do arithmetic — the result carries the correct dimension; name it and the compiler checks it:

cpp
square_meters     area  = 15.0_m * 5.0_m;    // m * m -> area
meters_per_second speed = 60.0_mi / 1.0_hr;   // -> velocity
meters            side  = sqrt(area / 3.0);   //  functions are unit-aware (found by ADL)

Get a plain number back out at the boundary with non-units code (there is no implicit quantity → double, except for dimensionless quantities):

cpp
double v = speed.value();     // the value in the quantity's units
double t = speed.to();// cast to a chosen representation
std::cout (100.0) - fahrenheit(32.0);   // 100 K  (a temperature difference)
kelvin(celsius(0.0) - kelvin(0.0));   // 273.15 K

// point ± delta → move the point (compound assignment reads the rhs as a relative amount):
celsius t(20.0);
t += celsius(5.0);   // warm by 5 degrees → 25 °C   (still an absolute temperature)
t -= celsius(10.0);  // cool by 10 degrees → 15 °C

// point + point is disabled for OFFSET scales — summing two degrees-Celsius values adds their datums,
// which is arithmetically corrupt (20 °C + 5 °C is not 25 °C in any absolute sense):
// auto bad = celsius(20.0) + celsius(5.0);   // does not compile (by design)
// Zero-offset scales (kelvin, rankine) have no datum to corrupt, so they add like any linear unit.

Comparisons (==, `` / delta<> wrappers

The point/delta distinction above is enforced quietly on plain units. When you want the compiler to enforce it in the type — so a function that takes a temperature difference cannot be handed an absolute temperature, or an epoch cannot be added to an epoch — reach for the two opt-in wrappers.

They live in their own header, so they are strictly opt-in: nothing about them exists until you ask for it.

cpp
#include    // the wrappers exist only where you include this

…

cpp
using namespace units;
using namespace units::temperature;

// point − point → delta (the datum cancels), kept in the LEFT operand's unit:
auto span = absolute>(100.0) - absolute>(32.0);  // delta of 100 °C-degrees
static_assert(traits::is_delta_v);

// point ± delta → point (move the point), delta ± delta → delta, delta */ scalar → delta:
auto warmer = absolute>(20.0) + delta>(5.0);        // 25 °C (a point)
delta> d(10.0);
d += delta>(18.0);   // +10 °C-degrees (mixed unit converts by degree size)
d *= 2.0;                               // 40 °C-degrees

// point + point is ill-formed — the sum of two points has no meaning:
// auto bad = absolute>(20.0) + absolute>(5.0);     // does not compile

…

cpp
#include 
using namespace units;
using namespace units::length;

kind> r(5.0);
kind> s(3.0);
auto ok  = r + kind>(1.0);   // same kind → radial 6 m
// auto no = r + s;                                    // ill-formed: "cannot add two DIFFERENT kinds"

…

text
readable_add_incompatible.cpp:9:18: error: no match for ‘operator+’ (operand types are ‘units::length::meters’ and ‘units::time::seconds’)
    9 | auto bad = 1.0_m + 1.0_s; // ill-formed: cannot add length and time
      |            ~~~~~ ^ ~~~~~
      |            |       |
      |            |       units::time::seconds
      |            units::length::meters

Assigning a product to the wrong dimension — m * m is an area, not a length. GCC reports the result through an internal alias with the named type beside it in {aka …}:

readable_wrong_result_type.cpp:10:41: error: conversion from ‘units::detail::rewrap_to_named_t >’ {aka ‘units::area::square_meters’} to non-scalar type ‘units::length::meters’ requested
   10 | units::length::meters a = 1.0_m * 1.0_m; // ill-formed: m*m is an area, not a length
      |                                   ~~~~~~^~~~~~~

…

cpp
double         distance_raw  (double mph, double sec)                        { return (mph * 1609.344 / 3600.0) * sec; }
meters distance_units(miles_per_hour v, seconds t)   { return v * t; }
asm
distance_raw:                        distance_units:
    mulsd   .LC0(%rip), %xmm0            mulsd   %xmm1, %xmm0
    divsd   .LC1(%rip), %xmm0            mulsd   .LC2(%rip), %xmm0
    mulsd   %xmm1, %xmm0                 divsd   .LC3(%rip), %xmm0
    ret                                  ret

A conversion between equivalent representations is free. Passing a meters where a meters is wanted is not a cheap conversion — it is no conversion:

cpp
double roundtrip(meters m) { meters copy = m; return copy.value(); }
asm
roundtrip:
    ret                              ; the whole function

A compile-time conversion is done by the compiler. A conversion of known values folds to a single constant load — the arithmetic never runs:

cpp
double speed_limit_mps() { return meters_per_second(65.0_mph).value(); }
asm
speed_limit_mps:
    movsd   .LC0(%rip), %xmm0        ; xmm0 = 29.0576  (65 mph, converted at compile time)
    ret

A hot loop vectorizes the same. Summing an array of kilometers as meters produces the identical instruction stream — including the AVX vectorization — as the raw-double loop; and

cpp
static_assert(1.0_km + 1.0_m == 1001.0_m);   // evaluated at compile time

…

cpp
#include 
#include 

using namespace units;
using namespace units::literals;

Eigen::Matrix, 3, 1> position;
position  range   = unit_norm(position);  // 3 m — the norm returns to the original dimension

A vector holds one scalar type, so same-dimension operations — construction, +/-, scaling, sum(), block and Map views, cast() — work directly on Eigen expressions. The operations whose result changes dimension (a dot product of lengths is an area; a cross product carries the product dimension) are provided as helpers that compute the dimensionally-correct type:

cpp
#include 

Eigen::Matrix,  3, 1> arm;
Eigen::Matrix, 3, 1> force;
// ...
auto area   = unit_dot(arm, arm);       // square_meters
auto moment = unit_cross(arm, force);   // a vector in newton_meters (torque)

// A dimensionless rotation / direction-cosine matrix applied to a dimensioned vector:
Eigen::Matrix          rotation = /* ... */;
Eigen::Matrix, 3, 1>  rotated  = unit_transform(rotation, position);

…

cpp
#include 
#include 
#include 
#include 

int main()
{
    using namespace units;
    using namespace units::literals;

    std::fstream file("speed.bin", std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);

    file >(file))
        std::cout value() >`), compares (`==`, and `` within a dimension), hashes (usable as an
`unordered_map` key), and renders to text — `to_string()` names the dimension when the library knows it
(`100 m`, `9.81 m s^-2`), or `to_string_raw()` for the always-available name-free form. `deserialize` returns
one too (wrapped in `std::expected`, since bad bytes can fail). Collapse an `any_unit` into a concrete quantity
with `to()` (checked, returns `std::expected`), `assign_to(out)` (mismatch-tolerant, assigns into an
existing variable and returns whether it fit), `try_to()` / `unit_cast()` (throwing), or `visit()`
(the canonical unit of the decoded dimension, no target named). `deserialize(bytes)` is the typed fast
path when the type is known.

> **Prefer the strongly-typed `unit` types; reach for `any_unit` only where you genuinely need type erasure.**
> `any_unit` trades compile-time dimension checking for a runtime-carried dimension, so it is the right tool at a
> boundary that loses the static type — **serialization and deserialization**, wire transport, or a heterogeneous
> stream whose dimension is not known until runtime. Everywhere the static type is available, the concrete `unit`
> types are better: the dimension is checked at compile time and there is no runtime dispatch or throw. One
> consequence to keep in mind: a dimensionless `any_unit` (a bare scalar, or a ratio such as `meters / meters`)
> resolves under a default `visit()` to `dimensionless`, so a ratio-scale like `percent` cannot be recovered from
> the erased form — name it explicitly (`to>()`) if you need that scale back.

**It also drops into byte interfaces with no cast.** Away from a stream, an `any_unit` exposes a modern,
type-safe byte view (`bytes()` → `std::span`) and a C-interface pair (`data()` → `const char*`,
`size()`) that feeds `std::fwrite`, a socket `send`, or `memcpy` directly:

```cpp
any_unit q = serialize(position);

std::fwrite(q.data(), 1, q.size(), fp);         // C stdio — no cast
::send(sock, q.data(), q.size(), 0);            // const char* decays to const void*

auto same = deserialize(q);                     // an any_unit converts to a span — round-trips directly

The stream identifies each base dimension by an 8-byte hash of its name, so the format has no fixed set of dimensions and no ceiling on how many a quantity composes: any base dimension round-trips, including one you define with make_dimension<>, with no central registry and no reflection. Values ride in SI canonical base in the tersest exact encoding (integer varint, 32-bit float, or 64-bit double), so a single-term integer quantity is a handful of bytes.

Bytes per serialized quantity across a spread, beside a naive {"value":V,"unit":"U"} JSON string for the same quantity (the JSON needs both peers to agree on the unit out of band; the binary carries the dimension itself):

Quantity Serialized bytes Naive JSON string
100.0_m 14 24
5000.0_g (5 kg) 13 23
1.0_GB 17 23
20.0_degC 20 26
60.0_mph 29 25
dimensionless(0.25) 7 —

Full guide, wire format, error model, and measured compile-time and run-time numbers: Serialization.


Formatting with std::format

Every quantity works with `std::format

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C++compile-timecpp14dimensional-analysisheader-only

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理