Unit Conversion and Dimensional Analysis Library
2.3.0
A compile-time c++14 unit conversion library
|
A compile-time, header-only, dimensional analysis library built on c++14 with no dependencies.
If you are using units.h
in production code, I'd love to hear from you via GitHub issues!
This version removes support for the Visual Studio 2013 compiler.
Features:
name()
and abbreviation()
member functions, which do not really on string/iostream.++
,--
), as well as unary +
operator.Bug fixs:
Features:
std::numeric_limits
of unit types.-=
, +=
, /=
, *=
.min
and max
overloads for units types in units::math
.to_string
function and abbreviation
functions: bits
, bytes
, bits_per_second
, and bytes_per_second
.value()
member for accessing underlying type.value_type
trait, as a synonym for underlying_type
.units
now supports cmake install and find_packages
. From the pull request: Bug fixes:
siemen
to be siemens
(Thanks @Oxyd)cubrt
operation (Thanks @PearCoding)Does this library work on your compiler? If so, let me know!
<cmath>
Functionsunit_t
The full documentation is available here.
The library consists of a single file (units.h), plus unit tests. To incorporate the library into your project, simply copy the header into a location in your include path, or add the included CMake project into your build. Using the CMake project, you can also build the unit tests and documentation if desired.
The library provides a set of types, containers, and traits to solve dimensional analysis problems, that is, problems involving dimensioned physical quantities. The conversions between units are defined as ratios at compile time, making the library incredibly fast. Additionally, specifying units as types, rather than variable suffixes (or not at all), provides complete type-safety within the compiler. This means that code that accidentally misuses units or which has errors in the dimensional analysis will fail at compile-time, not at run-time.
The unit test file unitTests/main.cpp
contains example usage of every type, trait, and function contained in the library, and while not exactly user-friendly, can be a valuable resource.
Add units.h
to your project, along with the using
directive for literals
Each "dimension" of unit is defined in its own namespace. See the namespaces section for a complete list. The rest of the guide assumes you've included the namespaces you plan to use:
The easiest way to get started with the units
library is to think of unit containers as double
values. Unit containers are typically the units' non-plural name with the suffix _t
(for type), e.g. meter_t
. See the documentation for a complete list.
Units can (and should!) be used anywhere double
values can be used:
What makes unit types special is that unit conversions happen implicitly and automatically. Since unit conversions are evaluated at compile time, this means you can mix and match all the unit types you want with no runtime penalty.
Note the return type has the correct dimensions of area, even though the source types were all units of length. units.h
has powerful dimensional analysis capabilities. But what happens if we get the return type wrong?
E:/workspace/units/include/units.h(1405): error C2338: Units are not compatible.
Your compiler will produce an "incompatible units" error if your dimensional analysis is incorrect. If your resulting unit types are complex, you could use auto
for simplicity:
NOTE: Think carefully about using auto
for return types. When you explicitly declare the return type, the compiler can check the dimensional analysis for correctness, and produce errors at compile time if you make a mistake. When using auto
, you are basically saying that whatever unit the right-hand side of the expression results to is correct (even if it's not). If you are only using auto
because a complex unit type is not available in the library, try defining a new unit as a better alternative.
More complex mathematical operations (almost every <cmath>
operation actually), including exponentials and square roots are possibe by using the units::math
namespace .
There are several ways to initialize unit values:
make_unit<...>()
factory. The syntax is familiar to boost::units
users, and allows explicit reference to the unit type for member variable initialization.Unit tags are the foundation of the unit library. Unit tags are types which are never instantiated in user code, but which provide the meta-information about different units, including how to convert between them, and how to determine their compatibility for conversion.
All unit tags are defined in namespaces under the units
namespace, such as units::length
or units::angle
, to avoid name clashes between units of different physical quantities which share the same names (like pounds). SI base units are defined as "categories" in the unit
namespace.
Units are defined in terms of
pi
fahrenheit
and celsius
)All units have their origin in the Système International (SI) base unit system. A special exception is made for angle units, which are defined in SI as ( m * m^-1), and in this library they are treated as a basic unit type because of their important engineering applications.
Example: the definitions of some common length units are:
Unit containers are the primary classes which will be instantiated in user code. They can be thought of as essentially equivalent to a double
, except that they have unit type tags associated with them. They can be used wherever a double would be used to store a dimensioned quantity. Containers are derived from the unit_t
class, and have the form [unitname]_t
, e.g. meter_t
or radian_t
.
Unit containers are defined in terms of the units they represent, their underlying type, and an optional non-linear scale (think decibels or Richter scale). For example, meter_t
would be defined:
or simply
since the underlying type and scale parameters default to double
and linear_scale
respectively.
Units of compatible types (e.g length units) can be implicitly converted/assigned to one another. Units (with the exception of dimensionless types) cannot be implicitly converted to/from built-in types, such as double
.
Units are constructed from built-in types, and the toDouble()
method (or operator()
) can be used to retrieve a built-in type value. That said, the user should prefer to operate within the unit type-space as much as is practical, and wrappers of most <cmath>
functions are provided to enable operating solely in the unit_t
domain.
The primary purpose of unit containers is to provide type safety and dimensional analysis for mathematical operations. for instance, the velocity of an object can be calculated:
The resulting velocity type will be deduced to be velocity::meters_per_second
with a value of 50.0. Additionally, if the return type if specified, the type system will verify that the units are compatible. For example, the following will fail to compile:
``cpp units::velocity::meters_per_second objectVelocity = square_meter_t(100.0) / second_t(2.0); // Error: Unit types are not compatible.
Arithmetic can be performed on unit containers the same way it can for built-in types. However, unlike built-in types, the return value of unit-type arithmetic will be the proper unit to represent the resulting quantity.
Unsupported arithmetic, or improper return types will result in compiler errors:
By providing explicit return types for unit functions, the compiler can be used to verify the accuracy of the dimensional analysis, and thus avoiding costly errors.
If you are using a compiler which supports user-defined literals (e.g. not Visual Studio 2013), then unit literals can be a convenient way to initialize and work with unit values:
Literals can also be used for any temporary values in calculations, making them more readable:
All literals* are defined by their SI abbreviation preceded by an underscore, e.g. _m
for meter. "Square" units are preceded by _sq
, e.g. _sq_m
for square meters. Non SI units use their most common abbreviations.
All literals are defined in the units::literals
namespace, and in order to use literals in your code you must include the line using units::literals
(since there is no way to put a namespace on an operator).
* with the exception of Teslas
, which use _Te
for compatibility with MSVC compilers.
The units
library include type-safe unit_t container wrappers for almost all of the <cmath>
functions, including the c++11 extensions. These functions can be found in the units::math
namespace. The units
library versions don't conflict with <cmath>
, and it's possible to use both libraries in the same code.
The overloaded functions ensure that only the proper unit types are accepted into the functions, and that the return value type matches the expected units, all without needing to result to the type-unsafe toDouble()
member.
In rare cases, the overload resolution for a given type may be ambiguous. If so, simply prepend the function with the fully-qualified units::math
prefix, e.g.
Many functions require units to be raised to some power. This can be accomplished using the units::math::pow
function:
The only constraint is that the exponential power (given in the template argument) must be known at compile time, so that the type system can deduce the output type. This differs from the <cmath> pow
implementation, which takes exponent values at runtime.
Square roots are also provided with the units::math::sqrt
function. Due to the nature of the sqrt
operation, the units library can often provide exact conversions for square root operations, but not in every case. The rest of the time, the sqrt
unit will be a rational_approximation of the real value. These are guaranteed to be accurate to at least 10 decimal places.
When interfacing with APIs, libraries, and frameworks which aren't unit
enabled, it may be necessary (if regrettable) to remove the type-safety of a unit container and expose its underlying type. This is possible using the unit_cast
function, or the to<>
member function.
Both functions produce the same results, the choice of syntax is simply a user preference.
To determine the underlying type of the unit container, the (verbose) trait units::traits::unit_t_traits<decltype(dist)>::underlying_type
could be used.
Complex, recursively-defined conversions are performed in just 5 instructions:
year_t twoYears(2.0); week_t twoYearsInWeeks = twoYears; 00007FF7BDB57FF6 xorps xmm9,xmm9 00007FF7BDB57FFA cvtsi2sd xmm9,rax 00007FF7BDB57FFF mulsd xmm9,mmword ptr [__real@4000000000000000 (07FF7BDBB31A0h)] 00007FF7BDB58008 divsd xmm9,mmword ptr [__real@401c000000000000 (07FF7BDBB33C0h)] 00007FF7BDB58011 movsd mmword ptr [rbp+6Fh],xmm9 EXPECT_EQ(week_t(104.286), twoYearsInWeeks); 00007FF7BDB58017 ...
In the library, the year to week conversion is defined in terms of years -> days -> hours -> minutes -> seconds -> minutes -> hours -> days -> weeks
but the total conversion ratio is computed at compile-time and the math is optimized to two floating-point operations.
Unit conversions between equivalent types are optimized away completely, and generate no machine code.
In many cases, unit equations are used to determine derived values from a set of values which are known at compile-time. In these situations, it would be optimal to pre-compute the derived values at compile time, thus generating no machine code and incurring no run-time penalty.
The unit_value_t
class is the mechanism in the units library to perform compile-time arithmetic. The unit_value_t
class functions exactly the same way as std::ratio
, but with an associated unit tag and the ensuing type safety.
For a simple example, let's define a right triangle whose hypotenuse is the sum of the squares of its side (a Pythagorean triple)
The definition above is perfectly efficient, as it generates no run-time code whatsoever, and still provides all the type safety of unit containers. The values of a
, b
, and c
can be accessed at runtime using the static value()
method of unit_value_t
``cpp auto a = RightTriangle::a::value(); // a is
meter_t(3) auto b = RightTriangle::b::value(); // b is
meter_t(4) auto c = RightTriangle::c::value(); // c is
meter_t(5)
``
The available compile-time operations are:
units::unit_value_add
units::unit_value_subtract
units::unit_value_multiply
units::unit_value_divide
units::unit_value_power
units::unit_value_sqrt
The preferred method of conversion is implicitly though the use of unit containers, however unit conversion can be accomplished using units::convert
for arithmetic types:
For type-safe conversion, prefer implicit conversion via unit_t type containers..
Unit tags and containers are split into separate namespaces to avoid conflicting unit names which represent different physical quantities.
Unit tag and unit_t
container definitions are defined in the following namespaces:
Literal values for unit containers are defined in the literals
namespace
Mathematical operations like sin
, log
, floor
, etc are defined in the following namespaces:
Type traits that you can use to test unit types are defined in the following namespaces:
The units library strives to provide built-in types for every conceivable unit, and before defining your own units you should double-check the namespaces to make sure it's not already included. That said, if you need to roll your own units, the library is extensible by design.
Defining new units is simple, as they can be recursively defined as ratio of previously-defined units in a way that mimics natural language and is highly readable:
Units are defined in the form: using [unit] = unit<std::ratio<[number of base units per unit]>, [base unit]>;
, where:
[unit]
is what you are defining.[base unit]
is the unit that [unit]
will be defined in terms of, and[number of base units per unit]
is the conversion ratio between the two, expressed as a std::ratio
type.Compound units are defined in a similar manner, with additional helper functions for polynomials:
using acceleration = compound_unit<meters, inverse<squared<seconds>>>; // (m / s^2)
The available helpers are:
units::inverse<...>
(inverts the unit, e.g. meters becomes meters^-1, or 1 / meters)units::squared<...>
(squares the unit, e.g. meters becomes meters^2)units::cubed<...>
(cubes the unit, e.g. meters becomes meters^3)units::square_root<...>
(takes the square root of the unit, e.g meters^2 becomes meters)units::atto<...>
through units::exa<...>
metric prefixesVersion 2.1.0
of the units library simplifies the task of adding new units by introducing a set of macros for unit definitions:
UNIT_ADD(namespaceName, nameSingular, namePlural, abbreviation, definition)
This macro adds a single new unit to the given namespace, as well as a literal definition and cout
support based on the given abbreviation
. e.g.
Would create the units::length::feet
tag, the units::length::foot_t
container type, and the _ft
literal.
UNIT_ADD_WITH_METRIC_PREFIXES(namespaceName, nameSingular, namePlural, abbreviation, definition)
This macro has the same functionality as UNIT_ADD
, but additionally adds unit types with all metric prefixes from femto
to peta
(smaller and larger prefixes mostly result in arithmetic overflow).
This macro has the same functionality as UNIT_ADD
, but additionally adds an underlyingType
parameter, which can be used to create units with integral, or other underlying types. The library default underlying type is double
.
UNIT_ADD_DECIBEL(namespaceName, nameSingular, abbreviation)
Adds the decibel representation for a previously-defined unit. e.g.
Adds the dBW_t
container, and the _dBW
literal.
UNIT_ADD_CATEGORY_TRAIT(unitCategory, baseUnit)
This macro creates a type-trait to check whether a unit is of a certain category, e.g. length. This is only necessary if defining new categories of units which are not included in units.h
at all. e.g.
Adds the units::traits::is_length_unit
trait.
The units library provides a comprehensive set of type-traits, which can be used in templated user code to enforce that the unit types have certain properties.
For example, let's say you want to write a function that validates that the square footage of an office (given in any units), meets the minimum size required by local ordinance.
This function will fail to compile if Units
is not a unit of area (since incompatible unit types are not comparable), but it will produce a series difficult-to-understand template errors. Type traits could be used to make the error message more friendly:
See the units::traits
namespace for a list of all the supported traits.
The default underlying type for all unit containers is double
. However, this can be overridden by providing a definition for UNIT_LIB_DEFAULT_TYPE
, e.g.
**_NOTE:_ changing the underlying type may result in unexpected behavior.** Unit conversion makes heavy use of division, which may make integral types unsuitable except for niche embedded applications. Using excessively large types may increase the number of arithmetic overflow errors.
For some embedded applications, it may be desirable to remove all references to <iostream>
in order to reduce compiled binary size and RAM requirements. There are two ways to accomplish this:
units.h
into your project include directory, then simply define UNIT_LIB_DISABLE_IOSTREAM
before including the header.units
in your project as a CMake
target (using add_subdirectory
), then all you need to do is set the DISABLE_IOSTREAM
cache option, either using the cmake-gui, or by adding the option to the cmake command line during configuration:If you know that you only need a subset of the unit namespaces for your application, you can dramatically improve compilation time by disabling the default definitions, and then only opting-in to the namespaces you want. For example:
The generic algorithm is
#define DISABLE_PREDEFINED_UNITS
#define ENABLE_PREDEFINED_<namepsace name>_UNITS
Additionally, for CMake
users, there are equivalently-named cmake options defined which will automatically include the preprocessor definitions in your project.
With certain compilers, it is possible that system header files like <ctype.h>
will define macros which conflict with the unit literals, which use SI abbreviations. In these cases, it is general safe and advisable to #undef
the offending macros.
_T
is known to conflict, but is hardcoded into the compiler and can't be disabled. For this reason, Tesla
units use the _Te
abbreviation.
The following macros may need to be undefined on the Windows platform to use units
:
The following macros may need to be undefined on the ARM platform to use units::literals
:
It's best to undefine macros on an as-needed basis.
There are several ways to incorporate units.h
into your project. The simplest is to just copy include/units.h
into your project include directory (which the licensing allows you to do). However, you'll have to properly set up the necessary compilation flags for C++14 (-std=c++14
on gcc).
However, if you are already using CMake as your build system, the recommended way to include units
is to copy the entire units
project as a subdirectory within your own top-level project folder. Then, in your CMakeLists.txt file add
Also, if you are distributing headers that depends on units.h, you shoud consider using cmake's find_package
to check if the header is installed on the user's system:
```cmake find_package(units) add_library(${PROJECT_NAME} my_lib.cpp) target_link_libraries(${PROJECT_NAME} units::units) ```
The include path properties are part of the units
target, so adding it as a subdirectory and linking against it is all you need to do, no need to worry about additional include directories.
If you don't care about the unit tests, you can minimize compile time by invoking CMake with the following option:
The library itself consists of a single header units.h, and can be included into your project without being built.
The unit tests and documentation can be built with CMake. A doxygen installation is required to generate the documentation, and a Tex install is needed if pdf documentation is desired.
To build the tests:
cmake
is installed, and that the bin
directory is in your PATH%
variable, and that a compiler like Visual Studio 2015 Community Edition
is installed..zip
package.cmd
terminal and navigate to the source directory.md build
cd build
cmake -Wno-dev ..
cmake --build . --config Release
unitLibTest.exe
in the folder build/unitTests/Release
.cmake --version
.gcc --version
..tar.gz
package.mkdir build
cd build
cmake -Wno-dev ..
cmake --build . --config Release
unitLibTest
in the folder build/unitTests
.v2.0.3
unit_t
types are now trivial types.unit_t
types support the unary minus (negation) operator.unit_value_t
.<cmath>
functions, including c++11 extensions.unit
, unit_t
, and unit_value_t
.v1.3.0
v1.2.2
v1.2.0
v1.1.1
v1.0.0