{"id":13419101,"url":"https://github.com/nholthaus/units","last_synced_at":"2025-05-14T19:02:23.796Z","repository":{"id":41329829,"uuid":"50688995","full_name":"nholthaus/units","owner":"nholthaus","description":"a compile-time, header-only, dimensional analysis and unit conversion library built on c++14 with no dependencies.","archived":false,"fork":false,"pushed_at":"2025-01-22T21:50:31.000Z","size":15001,"stargazers_count":992,"open_issues_count":106,"forks_count":139,"subscribers_count":32,"default_branch":"master","last_synced_at":"2025-04-06T13:02:07.060Z","etag":null,"topics":["compile-time","cpp14","dimensional-analysis","header-only","no-dependencies","template-metaprogramming","unit-conversion"],"latest_commit_sha":null,"homepage":"http://nholthaus.github.io/units/","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nholthaus.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-01-29T20:22:58.000Z","updated_at":"2025-04-03T12:15:43.000Z","dependencies_parsed_at":"2024-01-06T14:50:09.526Z","dependency_job_id":"d99c56ce-0a98-4d20-a494-e7d09a6dc74c","html_url":"https://github.com/nholthaus/units","commit_stats":{"total_commits":351,"total_committers":31,"mean_commits":11.32258064516129,"dds":"0.37891737891737887","last_synced_commit":"3ca0e22c5e5088a93f930617d193e895eb538bca"},"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nholthaus%2Funits","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nholthaus%2Funits/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nholthaus%2Funits/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nholthaus%2Funits/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nholthaus","download_url":"https://codeload.github.com/nholthaus/units/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248741147,"owners_count":21154249,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["compile-time","cpp14","dimensional-analysis","header-only","no-dependencies","template-metaprogramming","unit-conversion"],"created_at":"2024-07-30T22:01:11.337Z","updated_at":"2025-04-13T15:50:40.043Z","avatar_url":"https://github.com/nholthaus.png","language":"C++","readme":"\n# UNITS \nA compile-time, header-only, dimensional analysis library built on c++14 with no dependencies.\n\n[![Linux build](https://travis-ci.org/nholthaus/units.svg?branch=master)](https://travis-ci.org/nholthaus/units) [![Windows build](https://ci.appveyor.com/api/projects/status/github/nholthaus/units?svg=true\u0026branch=master)](https://ci.appveyor.com/project/nholthaus/units) [![Coverage Status](https://coveralls.io/repos/github/nholthaus/units/badge.svg?branch=master)](https://coveralls.io/github/nholthaus/units?branch=master) ![license](https://img.shields.io/badge/license-MIT-orange.svg) ![copyright](https://img.shields.io/badge/%C2%A9-Nic_Holthaus-orange.svg) ![language](https://img.shields.io/badge/language-c++-blue.svg) ![c++](https://img.shields.io/badge/std-c++14-blue.svg)\u003cbr\u003e![msvc2015](https://img.shields.io/badge/MSVC-2015-ff69b4.svg) ![msvc2017](https://img.shields.io/badge/MSVC-2017-ff69b4.svg) ![gcc-4.9.3](https://img.shields.io/badge/GCC-4.9.3-ff69b4.svg) ![gcc-5.4.0](https://img.shields.io/badge/GCC-5.4.0-ff69b4.svg) ![clang-3.4](https://img.shields.io/badge/CLANG-3.4-ff69b4.svg)\n\n# Get in touch\n\nIf you are using `units.h` in production code, I'd love to hear from you via GitHub issues!\n\n# Latest Release - v2.3.4\n\n## Get it\n[![DOWNLOAD](https://img.shields.io/badge/Download-v2.3.4-green.svg)](https://github.com/nholthaus/units/releases/tag/v2.3.4)\n\n## New in v2.3.4\n\n- Various bug fixes and improvements\n\n## New in v2.3.1\n\n**This version removes support for the Visual Studio 2013 compiler.**\n\nFeatures:\n- units now include constexpr `name()` and `abbreviation()` member functions, which do not really on string/iostream.\n- Builds with VS2017 Ninja generator out of the box\n- string conversions are now locale aware\n- added unary increment and decrement operators (`++`,`--`), as well as unary `+` operator.\n\nBug fixs:\n- fixed compilation error when iostream was disabled\n\n## New in v2.3.0\n\nFeatures:\n- 5x compile time improvement on MSVC.\n- 1.5x compile time improvement on GCC.\n- Even more dramatic reductions in compile time can be achieved if you opt-in to specific unit definitions instead of using all the library-defined types (which is the default value). Check out [Enabling a subset of units to improve compilation time](#enabling-a-subset-of-units-to-improve-compilation-time) for instructions.\n- Adds std::cout support for units with no defined abbreviation (they show up as a combination of SI base units)\n- Support for `std::numeric_limits` of unit types.\n- Assignment operators for unit types: `-=`, `+=`, `/=`, `*=`.\n- Added `min` and `max` overloads for units types in `units::math`.\n- Added `to_string` function and `abbreviation` functions:\n  ```cpp\n  auto len = 3.5_m;\n  auto str = units::length::to_string(len);\n  auto abv = units::length::abbreviation(len);\n\n  std::cout \u003c\u003c str;  // prints \"3.5 m\"\n  std::cout \u003c\u003c abv;  // prints \"m\"\n  ```\n- Added units of data and data transfer: `bits`, `bytes`, `bits_per_second`, and `bytes_per_second`.\n- Adds `value()` member for accessing underlying type.\n- Adds `value_type` trait, as a synonym for `underlying_type`.\n- Adds definitions for Julian and Gregorian years.\n- Thanks to @dinocore1, `units` now supports cmake install and `find_packages`. From the [pull request](https://github.com/nholthaus/units/pull/84):\n  ```cmake\n  # To have cmake install units library to a local 'install' directory:\n  mkdir build\n  cd build\n  cmake -DCMAKE_INSTALL_PREFIX=\"install\" ..\n  cmake --build . --target install\n  # The units library can then be used in some other cmake project using \n  # the standard 'find_package' command. Like so:\n  find_package(units)\n  ```\nBug fixes:\n- Fixed singular name of `siemen` to be `siemens` (Thanks @Oxyd)\n- Fixed bug with `cubrt` operation (Thanks @PearCoding)\n- Fixed constexpr relational operators bug\n- Fixed exponential temperature conversions (Thanks @guarndt)\n \n## Tested on\n\n - gcc-4.9.3\n - gcc-5.4.0\n - clang-3.4\n - msvc2015\n - msvc2017\n\nDoes this library work on your compiler? If so, let me know!\n\n# Contents\n\n\u003c!-- TOC --\u003e\n\n- [UNITS](#units)\n- [Get in touch](#get-in-touch)\n- [Latest Release - v2.3.1](#latest-release---v231)\n\t- [Get it](#get-it)\n\t- [New in v2.3.1](#new-in-v231)\n\t- [New in v2.3.0](#new-in-v230)\n\t- [Tested on](#tested-on)\n- [Contents](#contents)\n- [Documentation](#documentation)\n- [Description](#description)\n- [Getting started guide](#getting-started-guide)\n- [Unit initialization](#unit-initialization)\n- [Unit tags](#unit-tags)\n- [Unit containers](#unit-containers)\n- [Unit Literals](#unit-literals)\n- [`\u003ccmath\u003e` Functions](#cmath-functions)\n- [Exponentials and Square Roots](#exponentials-and-square-roots)\n- [Removing type safety](#removing-type-safety)\n- [Efficiency](#efficiency)\n- [Pure Compile-time Unit Manipulation](#pure-compile-time-unit-manipulation)\n- [Conversion without unit containers](#conversion-without-unit-containers)\n- [Namespaces](#namespaces)\n- [Defining new units](#defining-new-units)\n- [Unit definition macros](#unit-definition-macros)\n- [Unit Type Traits](#unit-type-traits)\n- [Changing the underlying type of `unit_t`](#changing-the-underlying-type-of-unit_t)\n- [Disabling IOStream](#disabling-iostream)\n- [Enabling a subset of units to improve compilation time](#enabling-a-subset-of-units-to-improve-compilation-time)\n- [Macro clashes](#macro-clashes)\n\t- [Windows macros](#windows-macros)\n\t- [ARM macros](#arm-macros)\n- [CMake Instructions](#cmake-instructions)\n- [Build Instructions](#build-instructions)\n\t- [Windows](#windows)\n\t- [Linux](#linux)\n- [Previous Releases](#previous-releases)\n\n\u003c!-- /TOC --\u003e\n\n# Documentation\n\n[The full documentation is available ***here***](http://nholthaus.github.io/units).\n\n# Description\n\nThe library consists of a single file ([units.h](include/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](#cmake-instructions) into your build. Using the CMake project, you can also build the unit tests and documentation if desired.\n\nThe 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_. \n\nThe 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.\n\n# Getting started guide\n\nAdd `units.h` to your project, along with the `using` directive for literals\n\n```cpp\n#include \u003cunits.h\u003e\n\nusing namespace units::literals;\n```\n\nEach \"dimension\" of unit is defined in its own namespace. See [the namespaces section](#namespaces) for a complete list. The rest of the guide assumes you've included the namespaces you plan to use:\n\n```cpp\nusing namespace units;\nusing namespace units::length;\nusing namespace units::time;\nusing namespace units::area;\nusing namespace units::velocity;\n```\n\n**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](http://nholthaus.github.io/units/namespaces.html) for a complete list.\n\nUnits can (_and should!_) be used anywhere `double` values can be used:\n\n```cpp\ndouble          area = 15 * 5 + 10 * 10;                // 175 m^2?\nsquare_meter_t  area = 15_m * 5_m + 10_m * 10_m;        // 175 m^2\n```\n\nWhat 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_.\n\n```cpp\nfoot_t              len   = 5_m;                            // simple implicit conversion\nmeters_per_second_t speed = 60_mi / 1_hr;                   // more complex implicit conversion\nsquare_meter_t      area  = 15_m * 5_m + 1000_cm * 1000_cm; // previous example with mixed units\n```\n\nNote 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?\n\n```cpp\nmeter_t  area = 15_m * 5_m + 10_m * 10_m;               // oops, m * m = m^2\n```\n\n\u003e E:/workspace/units/include/units.h(1405): error C2338: Units are not compatible.\n\nYour 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:\n\n```cpp\nauto result = 15_m * 5_m + 10_m * 10_m;                 //  m^2\nauto speed  = 60_mi / 1_hr;                             //  60 mph\n```\n\n***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](#defining-new-units) as a better alternative.\n\nMore complex mathematical operations ([almost every `\u003ccmath\u003e` operation actually](http://nholthaus.github.io/units/namespaceunits_1_1math.html)), including exponentials and square roots are possibe by using the `units::math` namespace .\n\n```cpp\nusing namespace units::math;\n\nmeter_t a = 3_m;\nmeter_t b = 4_m;\nmeter_t c = sqrt(pow\u003c2\u003e(a) + pow\u003c2\u003e(b));    // Pythagorean threorem.\n\nstd::cout \u003c\u003c c \u003c\u003c std::endl;                // prints: \"5 m\"\n```\n# Unit initialization\n\nThere are several ways to initialize unit values:\n\n- Explicit initialization\n\n  ```cpp\n  meter_t distance_m(10); // Explicit initialization from double\n  meter_t distance(10_m); // Explicit initialization from unit literal\n  meter_t dist(100_ft);   // Explicit initialization from unit literal of a different type\n  ```\n\n- `make_unit\u003c...\u003e()` factory. The syntax is familiar to `boost::units` users, and allows explicit reference to the unit type for member variable initialization.\n\n   ```cpp\n   class myClass\n   {\n     public:\n       \n       myClass() : m_speed(make_unit\u003cmiles_per_hour_t\u003e(100)) {}\n\n     private:\n\n       miles_per_hour_t m_speed;\n   };\n   ```\n\n# Unit tags\nUnit 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.\n\nAll 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.\n\nUnits are defined in terms of \n 1. A scale factor relative to a base unit type.\n 2. A base unit\n 3. [optionally] a scale factor of `pi`\n 4. [optionally] a datum translation (such as the +/- 32 required to convert between `fahrenheit` and `celsius`)\n\n 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.\n \n_Example_: the definitions of some common length units are:\n\n```cpp\nnamespace length\n{\n\tusing meters = units::unit\u003cstd::ratio\u003c1\u003e, units::category::length_unit\u003e;\t// meters are (1) unit of length in the SI system.\n\tusing feet = units::unit\u003cstd::ratio\u003c381, 1250\u003e, meters\u003e;\t\t\t\t\t// feet are 0.3048 meters.\n}\n```\n\n# Unit containers\n\nUnit 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`.\n\nUnit 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: \n\n```cpp\nusing meter_t = units::unit_t\u003cunits::length::meter, double, units::linear_scale\u003e\n```\n\nor simply \n\n```cpp\nusing meter_t = units::unit_t\u003cunits::length::meter\u003e\n```\n\nsince the underlying type and scale parameters default to `double` and `linear_scale` respectively.\n\nUnits 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`. \n\nUnits 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 `\u003ccmath\u003e` functions are provided to enable operating solely in the `unit_t` domain. \n\nThe 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:\n\n```cpp\nauto objectVelocity = meter_t(100.0) / second_t(2.0);\n```\n\nThe 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:\n\n```cpp\nunits::velocity::meters_per_second objectVelocity = square_meter_t(100.0) / second_t(2.0); // Error: Unit types are not compatible.`\n```\n\nUnit containers can (and should!) be used to perform implicit conversions:\n\n```cpp\nunits::time::second_t a;\nunits::time::minute_t b(1.0);\n\na = b;\t// a == 60.0\n```\n\nArithmetic 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.\n\n```cpp\nusing namespace units::length;\nusing namespace units::area;\n\nmeter_t a_m(1.0), b_m(2.0), c_m;\nfoot_t\ta_ft(1.0), b_ft(2.0), c_ft;\n\nc_m = a_m + b_m;                            // OK. c == 3m\nc_ft = a_m + b_m;                           // OK. resulting 3m is converted to ft.\nauto result = a_m + b_ft;                   // OK. result is `meter_t` (left-most unit)\n\nauto result_sm = a_m * b_m;                 // OK. result_sm is `square_meter_t`.\nauto result_s = a_m / b_m;                  // OK. result_s is `dimensionless_t`.\nauto result = a_m * b_ft;                   // OK. result is `square_meter_t` (left-most unit)\n\nauto result = a_m * square_meter_t(1.0);    // OK. units can always be multiplied. Result is `cubed\u003cmeter_t\u003e`.\nauto result = a_m * scalar_t(1.0);          // OK. units can always be multiplied. Result is `meter_t`.\n```\n\t\nUnsupported arithmetic, or improper return types will result in compiler errors:\n\n```cpp\nc_m = a_m + 5.0;                            // Error. can't add scalars to dimensioned units.\nc_m = a_m + scalar_t(5.0);                  // Error. can't add scalars to dimensioned units.\nauto result = a_m + square_meter_t(1.0);    // Error. Incompatible units.\n```\n\nBy 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.\n\n# Unit Literals\n\nIf 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:\n\n```cpp\nusing namespace units::literals;\n\nmeter_t dist\t= 10_m;\t\t// 10 m\nmeter_t dist2\t= 1_km;\t\t// 1000 m\n```\n\nLiterals can also be used for any temporary values in calculations, making them more readable:\n\n```cpp\nauto area = units::length::meter_t(5) * units::length::meter_t(10);\t// without literals\nauto area = 5_m * 10_m;\t\t\t\t\t\t\t// with literals\n```\n\nAll 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.\n\nAll literals can be used with a metric prefix as table shows:\n\n| Metric Prefix | Literal |  Example  |\n|:-------------:|:--------:|:---------:|\n|     femto     |     f    |  `10_fm`  |\n|      pico     |     p    |  `10_pm`  |\n|      nano     |     n    |  `10_nm`  |\n|     micro     |     u    |  `10_um`  |\n|     milli     |     m    |  `10_mm`  |\n|     centi     |     c    |  `10_cm`  |\n|      deci     |     d    |  `10_dm`  |\n|      deca     |    da    |  `10_dam` |\n|     hecto     |     h    |  `10_hm`  |\n|      kilo     |     k    |  `10_km`  |\n|      mega     |     M    |  `10_Mm`  |\n|      giga     |     G    |  `10_Gm`  |\n|      tera     |     T    |  `10_Tm`  |\n|      peta     |     P    |  `10_Pm`  |\n\nAll 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).\n\n_* with the exception of `Teslas`, which use `_Te` for compatibility with MSVC compilers._\n\n# `\u003ccmath\u003e` Functions\n\nThe `units` library include type-safe unit_t container wrappers for almost all of the `\u003ccmath\u003e` functions, _including_ the c++11 extensions. These functions can be found in the `units::math` namespace. The `units` library versions don't conflict with `\u003ccmath\u003e`, and it's possible to use both libraries in the same code. \n\nThe 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.\n\nIn _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.\n\n```cpp\nmeter_t x(2.0);\nmeter_t y(3.0);\nsquare_meter_t z(1.0);\nsquare_meter_t result;\n\nresult = fma(x, y, z);\t\t\t\t\t\t\t\t\t\t\t\t// Error: ambiguous\ndouble result = fma(x.toDouble(), y.toDouble(), z.toDouble());\t\t// Warning: Unsafe!\nresult = math::fma(x, y, z);\t\t\t\t\t\t\t\t\t\t// OK.\n```\n\n# Exponentials and Square Roots\n\nMany functions require units to be raised to some power. This can be accomplished using the `units::math::pow` function:\n\n```cpp\nsquare_meter_t m2 = units::math::pow\u003c2\u003e(meter_t(5.0));\t// m2 == 25.0\n```\n\nThe 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 `\u003ccmath\u003e pow` implementation, which takes exponent values at runtime.\n\nSquare 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.\n\n```cpp\nmeter_t m = units::math::sqrt(square_meter_t(4.0));\t\t// m == 2.0\n```\n\n# Removing type safety\n\nWhen 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\u003c\u003e` member function.\n\n```cpp\nusing namespace units;\nusing namespace units::length;\n\n// Get double value from a unit container (double is the default underlying type of the units library)\nmeter_t dist(10);\ndouble dval = unit_cast\u003cdouble\u003e(dist);\ndouble dval2 = dist.to\u003cdouble\u003e();\n\n// Get integer value (potentially narrowing, be careful!)\nint ival = unit_cast\u003cint\u003e(dist);\nint ival2 = dist.to\u003cint\u003e();\n```\n\nBoth functions produce the same results, the choice of syntax is simply a user preference.\n\nTo determine the underlying type of the unit container, the (verbose) trait `units::traits::unit_t_traits\u003cdecltype(dist)\u003e::underlying_type` could be used.\n\n# Efficiency\n\nComplex, recursively-defined conversions are performed in just 5 instructions:\n\n\t\tyear_t twoYears(2.0);\n\t\tweek_t twoYearsInWeeks = twoYears;\n\t00007FF7BDB57FF6  xorps       xmm9,xmm9  \n\t00007FF7BDB57FFA  cvtsi2sd    xmm9,rax  \n\t00007FF7BDB57FFF  mulsd       xmm9,mmword ptr [__real@4000000000000000 (07FF7BDBB31A0h)]  \n\t00007FF7BDB58008  divsd       xmm9,mmword ptr [__real@401c000000000000 (07FF7BDBB33C0h)]  \n\t00007FF7BDB58011  movsd       mmword ptr [rbp+6Fh],xmm9  \n\t\tEXPECT_EQ(week_t(104.286), twoYearsInWeeks);\n\t00007FF7BDB58017  ...\n\nIn the library, the year to week conversion is defined in terms of\n`years -\u003e days -\u003e hours -\u003e minutes -\u003e seconds -\u003e minutes -\u003e hours -\u003e days -\u003e weeks`\nbut the total conversion ratio is computed at compile-time and the math is optimized to two floating-point operations.\n\nUnit conversions between equivalent types are optimized away completely, and generate _no machine code_.\n\n# Pure Compile-time Unit Manipulation\n\nIn 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.\n\nThe `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.\n\nFor a simple example, let's define a right triangle whose hypotenuse is the sum of the squares of its side (a Pythagorean triple)\n\n```cpp\nstruct RightTriangle\n{\n\tusing a = unit_value_t\u003cmeters, 3\u003e;\n\tusing b = unit_value_t\u003cmeters, 4\u003e;\n\tusing c = unit_value_sqrt\u003cunit_value_add\u003cunit_value_power\u003ca, 2\u003e, unit_value_power\u003cb, 2\u003e\u003e\u003e;\n};\n```\n\t\nThe 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`\n\n```cpp\nauto a = RightTriangle::a::value();\t// a is `meter_t(3)`\nauto b = RightTriangle::b::value();\t// b is `meter_t(4)`\nauto c = RightTriangle::c::value();\t// c is `meter_t(5)`\n```\n\nThe available compile-time operations are:\n\n - `units::unit_value_add`\n - `units::unit_value_subtract`\n - `units::unit_value_multiply`\n - `units::unit_value_divide`\n - `units::unit_value_power`\n - `units::unit_value_sqrt`\n \n# Conversion without unit containers\n\nThe preferred method of conversion is implicitly though the use of unit containers, however unit conversion can be accomplished using `units::convert` for arithmetic types:\n\n```cpp\ndouble val_in = convert\u003cfeet, inches\u003e(1.0);\t// val_in == 12.0\n```\n\t\nFor type-safe conversion, prefer implicit conversion via unit_t type containers..\n\n# Namespaces\n\nUnit tags and containers are split into separate namespaces to avoid conflicting unit names which represent different physical quantities.\n\nUnit tag and `unit_t` container definitions are defined in the following namespaces:\n - units::length\n - units::mass\n - units::time\n - units::angle (plane)\n - units::current\n - units::temperature\n - units::substance (amount of, i.e. moles)\n - units::luminous_intensity\n - units::solid_angle\n - units::frequency\n - units::velocity\n - units::angular_velocity\n - units::acceleration\n - units::force\n - units::pressure\n - units::charge\n - units::energy\n - units::power\n - units::voltage\n - units::capacitance\n - units::impedance\n - units::magnetic_flux\n - units::magnetic_field_strength\n - units::inductance\n - units::luminous_flux\n - units::illuminance\n - units::radiation\n - units::torque\n - units::area\n - units::volume\n - units::density\n - units::concentration\n - units::data\n - units::data_transfer_rate\n - units::constants (scalar and non-scalar physical constants like Avogadro's number)\n \nLiteral values for unit containers are defined in the `literals` namespace\n- units::literals\n\nMathematical operations like `sin`, `log`, `floor`, etc are defined in the following namespaces:\n - units::math\n \nType traits that you can use to test unit types are defined in the following namespaces:\n - units::traits\n\n# Defining new units\n\nThe 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.\n\nDefining 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:\n\n```cpp\nnamespace time\n{\n\tusing seconds = units::unit\u003cstd::ratio\u003c1\u003e,   units::category::time_unit\u003e;\n\tusing minutes = units::unit\u003cstd::ratio\u003c60\u003e,  seconds\u003e;\n\tusing hours   = units::unit\u003cstd::ratio\u003c60\u003e,  minutes\u003e;\n\tusing days    = units::unit\u003cstd::ratio\u003c24\u003e,  hours\u003e;\n\tusing weeks   = units::unit\u003cstd::ratio\u003c7\u003e,   days\u003e;\n\tusing years   = units::unit\u003cstd::ratio\u003c365\u003e, days\u003e;\n}\n```\n\nUnits are defined in the form: `using [unit] = unit\u003cstd::ratio\u003c[number of base units per unit]\u003e, [base unit]\u003e;`, where:\n - the `[unit]` is what you are defining.\n - the `[base unit]` is the unit that `[unit]` will be defined in terms of, and\n - the `[number of base units per unit]` is the conversion ratio between the two, expressed as a `std::ratio` type.\n \nCompound units are defined in a similar manner, with additional helper functions for polynomials:\n\n\tusing acceleration = compound_unit\u003cmeters, inverse\u003csquared\u003cseconds\u003e\u003e\u003e;\t\t// (m / s^2)\n\t\nThe available helpers are:\n - `units::inverse\u003c...\u003e`     (inverts the unit, e.g. meters becomes meters^-1, or 1 / meters)\n - `units::squared\u003c...\u003e`     (squares the unit, e.g. meters becomes meters^2)\n - `units::cubed\u003c...\u003e`       (cubes the unit, e.g. meters becomes meters^3)\n - `units::square_root\u003c...\u003e` (takes the square root of the unit, e.g meters^2 becomes meters)\n - `units::atto\u003c...\u003e` through `units::exa\u003c...\u003e` metric prefixes\n\t\n# Unit definition macros\n\nVersion `2.1.0` of the units library simplifies the task of adding new units by introducing a set of macros for unit definitions:\n\n- `UNIT_ADD(namespaceName, nameSingular, namePlural, abbreviation, definition)`\n\n  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.\n\n  ```cpp\n  UNIT_ADD(length, foot, feet, ft, unit\u003cstd::ratio\u003c381, 1250\u003e, meters\u003e)\n  ```\n\n  Would create the `units::length::feet` tag, the `units::length::foot_t` container type, and the `_ft` literal.\n\n- `UNIT_ADD_WITH_METRIC_PREFIXES(namespaceName, nameSingular, namePlural, abbreviation, definition)`\n  \n  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).\n\n- `UNIT_ADD_WITH_CUSTOM_TYPE(namespaceName, nameSingular, namePlural, abbreviation, underlyingType, definition)`\n\n  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`.\n- `UNIT_ADD_DECIBEL(namespaceName, nameSingular, abbreviation)`\n\n  Adds the decibel representation for a previously-defined unit. e.g.\n\n  ```cpp\n  UNIT_ADD_DECIBEL(power, watt, dBW)\n  ```\n\n  Adds the `dBW_t` container, and the `_dBW` literal.\n\n- `UNIT_ADD_CATEGORY_TRAIT(unitCategory, baseUnit)`\n\n  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.\n\n  ```cpp\n  UNIT_ADD_CATEGORY_TRAIT(length, meter)\n  ```\n\n  Adds the `units::traits::is_length_unit` trait.\n\n# Unit Type Traits\n\nThe 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.\n\nFor 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. \n\n```cpp\ntemplate\u003ctypename Units\u003e\nbool isMinimumSize(Units x)\n{\n\treturn x \u003e= square_feet_t(80.0);\n}\n```\n\t\nThis 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:\n\n```cpp\ntemplate\u003ctypename Units\u003e\nbool isMinimumSize(Units x)\n{\n\tstatic_assert(units::traits::is_area_unit\u003cUnits\u003e::value, \"Input value x must represent an area quantity.\");\n\treturn x \u003e= square_feet_t(80.0);\n}\n```\n\nSee the `units::traits` namespace for a list of all the supported traits.\n\n# Changing the underlying type of `unit_t`\n\nThe 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.\n\n```cpp\n// Use 64-bit integers as the underlying unit type\n#define UNIT_LIB_DEFAULT_TYPE int64_t\n#include \u003cunits.h\u003e\n```\n\n**_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.\n\n# Disabling IOStream\n\nFor some embedded applications, it may be [desirable to remove all references to `\u003ciostream\u003e` in order to reduce compiled binary size and RAM requirements](https://github.com/nholthaus/units/issues/32). There are two ways to accomplish this:\n\n1. If you are copy/pasting `units.h` into your project include directory, then simply define `UNIT_LIB_DISABLE_IOSTREAM` before including the header.\n\n   ```cpp\n   #define UNIT_LIB_DISABLE_IOSTREAM\n   #include \u003cunits.h\u003e\n   ```\n\n2. If you are including `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:\n\n   ```bash\n   cmake -DDISABLE_IOSTREAM=ON -DBUILD_TESTS=OFF ..\n   cmake --build . --config Release\n   ```\n\n# Enabling a subset of units to improve compilation time\n\nIf 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:\n\n  ```cpp\n  // Only use length and time\n  #define DISABLE_PREDEFINED_UNITS\n  #define ENABLE_PREDEFINED_LENGTH_UNITS\n  #define ENABLE_PREDEFINED_TIME_UNITS\n  ```\n\nThe generic algorithm is\n  1. disable the pre-defined units using `#define DISABLE_PREDEFINED_UNITS`\n  2. opt-in to the namespaces you want using `#define ENABLE_PREDEFINED_\u003cnamepsace name\u003e_UNITS`\n\nAdditionally, for `CMake` users, there are equivalently-named cmake options defined which will automatically include the preprocessor definitions in your project. Alternatively, you can use `add_definitions()` in your cmake file to set macros globally::\n\n  ```cpp\n  // Only use length and time\n  add_definitions(\n  \t-DDISABLE_PREDEFINED_UNITS\n  \t-DENABLE_PREDEFINED_LENGTH_UNITS\n  \t-DENABLE_PREDEFINED_TIME_UNITS\n  )\n  ```\n  \nBe aware, some units depend on others. See the unit dependencies table bellow:\n\n|           Unit          |           Dependencies           |\n|:-----------------------:|:--------------------------------:|\n|       ACCELERATION      |           LENGTH, TIME           |\n|     ANGULAR_VELOCITY    |            ANGLE, TIME           |\n|           AREA          |              LENGTH              |\n|         DENSITY         |           MASS, VOLUME           |\n|          FORCE          | ACCELERATION, LENGTH, MASS, TIME |\n|       ILLUMINANCE       |       LENGTH, LUMINOUS_FLUX      |\n| MAGNETIC_FIELD_STRENGTH |           MAGNETIC_FLUX          |\n|         PRESSURE        |           FORCE, LENGTH          |\n|        RADIATION        |           ENERGY, MASS           |\n|       SOLID_ANGLE       |               ANGLE              |\n|          TORQUE         |           FORCE, LENGTH          |\n|         VELOCITY        |           LENGTH, TIME           |\n|          VOLUME         |              LENGTH              |\n\n# Macro clashes\n\nWith certain compilers, it is possible that system header files like `\u003cctype.h\u003e` 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.\n\n## Windows macros\n\n`_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.\n\nThe following macros may need to be undefined on the Windows platform to use `units`:\n\n   ```cpp\n   #undef pascal\n   #include \u003cunits.h\u003e\n   ```\n   \n## ARM macros\n\nThe following macros may need to be undefined on the ARM platform to use `units::literals`:\n\n   ```cpp\n   #undef _U\n   #undef _L\n   #undef _N\n   #undef _S\n   #undef _P\n   #undef _C\n   #undef _X\n   #undef _B\n   #define UNIT_LIB_DISABLE_IOSTREAM // it's prudent to disable IOStream on embedded platforms as well.\n   #include \u003cunits.h\u003e\n   ```\n\n   It's best to undefine macros on an as-needed basis.\n\n# CMake Instructions\n\nThere 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).\n\nHowever, 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\n\n   ```cmake\n   add_subdirectory(units)\n\n   add_executable(${PROJECT_NAME} main.cpp)\n   target_link_libraries(${PROJECT_NAME} units)\n   ```\n\nAlso, 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:\n    \n    ```cmake\n    find_package(units)\n    \n    add_library(${PROJECT_NAME} my_lib.cpp)\n    target_link_libraries(${PROJECT_NAME} units::units)\n    ```\n\nThe 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.\n\nIf you don't care about the unit tests, you can minimize compile time by invoking CMake with the following option:\n\n   ```bash\n   cmake -DBUILD_TESTS=OFF ..\n   cmake -build .\n   ```\n# Build Instructions\n\nThe library itself consists of a single header [units.h](include/units.h), and can be included into your project without being built. \n\nThe 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.\n\nTo build the tests:\n\n## Windows\n 1. Ensure [`cmake`](https://cmake.org/download/) is installed, and that the `bin` directory is in your `%PATH%` variable, and that a compiler like [`Visual Studio 2015 Community Edition`](https://www.visualstudio.com/post-download-vs?sku=community\u0026clcid=0x409\u0026downloadrename=true#) is installed.\n 2. clone the repository or download the `.zip` package.\n 3. Open a `cmd` terminal and navigate to the source directory.\n 4. Type the following commands:\n   - `md build`\n   - `cd build`\n   - `cmake -Wno-dev ..`\n   - `cmake --build . --config Release`\n 5. The tests will be created in an executable called `unitLibTest.exe` in the folder `build/unitTests/Release`.\n   \n## Linux\n 1. Ensure you are using cmake 3.2 or later. You can verify this with `cmake --version`.\n 2. Ensure you are using gcc version 4.9 or greater. You can verify this with `gcc --version`.\n 3. clone the repository or download the `.tar.gz` package.\n 4. Open a terminal and navigate to the source directory.\n 5. Type the following commands:\n   - `mkdir build`\n   - `cd build`\n   - `cmake -Wno-dev ..`\n   - `cmake --build . --config Release`\n 6. The tests will be created in an executable called `unitLibTest` in the folder `build/unitTests`.\n\n# Previous Releases\n\n - [`v2.0.3`](https://github.com/nholthaus/units/releases/tag/v2.0.3)  \n   - `unit_t` types are now trivial types.\n   - `unit_t` types support the unary minus (negation) operator.\n   - Compile-time unit arithmetic via `unit_value_t`.\n   - Unit-enabled ports of most `\u003ccmath\u003e` functions, including c++11 extensions.\n   - Square-root manipulators for `unit`, `unit_t`, and `unit_value_t`.\n   - Improved documentation.\n - [`v1.3.0`](https://github.com/nholthaus/units/releases/tag/v1.3.0)  \n   - Adds ostream support. \n   - bug fixes.\n - [`v1.2.2`](https://github.com/nholthaus/units/releases/tag/v1.2.2)  \n   - Bug fixes (#1) and namespace cleanup.\n - [`v1.2.0`](https://github.com/nholthaus/units/releases/tag/v1.2.0)  \n   - Adds angular velocity units.\n - [`v1.1.1`](https://github.com/nholthaus/units/releases/tag/v1.1.1)   \n   - Adds Doxygen and additional type traits.\n - [`v1.0.0`](https://github.com/nholthaus/units/releases/tag/v1.0.0)  \n   - Initial release.\n","funding_links":[],"categories":["TODO scan for Android support in followings","Units"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnholthaus%2Funits","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnholthaus%2Funits","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnholthaus%2Funits/lists"}