WPILibC++ 2025.0.0-alpha-1-24-g6478ba6
base.h
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5// Copyright (c) 2016 Nic Holthaus
6//
7// The MIT License (MIT)
8//
9// Permission is hereby granted, free of charge, to any person obtaining a copy
10// of this software and associated documentation files (the "Software"), to deal
11// in the Software without restriction, including without limitation the rights
12// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13// copies of the Software, and to permit persons to whom the Software is
14// furnished to do so, subject to the following conditions:
15//
16// The above copyright notice and this permission notice shall be included in
17// all copies or substantial portions of the Software.
18//
19// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25// SOFTWARE.
26//
27// ATTRIBUTION:
28// Parts of this work have been adapted from:
29// http://stackoverflow.com/questions/35069778/create-comparison-trait-for-template-classes-whose-parameters-are-in-a-different
30// http://stackoverflow.com/questions/28253399/check-traits-for-all-variadic-template-arguments/28253503
31// http://stackoverflow.com/questions/36321295/rational-approximation-of-square-root-of-stdratio-at-compile-time?noredirect=1#comment60266601_36321295
32//
33
34/// @file units.h
35/// @brief Complete implementation of `units` - a compile-time, header-only,
36/// unit conversion library built on c++14 with no dependencies.
37
38#pragma once
39
40#ifdef _MSC_VER
41# pragma push_macro("pascal")
42# undef pascal
43# if _MSC_VER <= 1800
44# define _ALLOW_KEYWORD_MACROS
45# pragma warning(push)
46# pragma warning(disable : 4520)
47# pragma push_macro("constexpr")
48# define constexpr /*constexpr*/
49# pragma push_macro("noexcept")
50# define noexcept throw()
51# endif // _MSC_VER < 1800
52#endif // _MSC_VER
53
54#if !defined(_MSC_VER) || _MSC_VER > 1800
55# define UNIT_HAS_LITERAL_SUPPORT
56#endif
57
58#ifndef UNIT_LIB_DEFAULT_TYPE
59# define UNIT_LIB_DEFAULT_TYPE double
60#endif
61
62//--------------------
63// INCLUDES
64//--------------------
65
66#include <chrono>
67#include <ratio>
68#include <type_traits>
69#include <cstdint>
70#include <cmath>
71#include <limits>
72
73#if defined(UNIT_LIB_ENABLE_IOSTREAM)
74 #include <iostream>
75 #include <locale>
76 #include <string>
77#endif
78#if __has_include(<fmt/format.h>) && !defined(UNIT_LIB_DISABLE_FMT)
79 #include <locale>
80 #include <string>
81 #include <fmt/format.h>
82#endif
83
84#include <gcem.hpp>
85
86//------------------------------
87// STRING FORMATTER
88//------------------------------
89
90namespace units
91{
92 namespace detail
93 {
94 template <typename T> std::string to_string(const T& t)
95 {
96 std::string str{ std::to_string(t) };
97 int offset{ 1 };
98
99 // remove trailing decimal points for integer value units. Locale aware!
100 struct lconv * lc;
101 lc = localeconv();
102 char decimalPoint = *lc->decimal_point;
103 if (str.find_last_not_of('0') == str.find(decimalPoint)) { offset = 0; }
104 str.erase(str.find_last_not_of('0') + offset, std::string::npos);
105 return str;
106 }
107 }
108}
109
110namespace units
111{
112 template<typename T> inline constexpr const char* name(const T&);
113 template<typename T> inline constexpr const char* abbreviation(const T&);
114}
115
116//------------------------------
117// MACROS
118//------------------------------
119
120/**
121 * @def UNIT_ADD_UNIT_TAGS(namespaceName,nameSingular, namePlural, abbreviation, definition)
122 * @brief Helper macro for generating the boiler-plate code generating the tags of a new unit.
123 * @details The macro generates singular, plural, and abbreviated forms
124 * of the unit definition (e.g. `meter`, `meters`, and `m`), as aliases for the
125 * unit tag.
126 * @param namespaceName namespace in which the new units will be encapsulated.
127 * @param nameSingular singular version of the unit name, e.g. 'meter'
128 * @param namePlural - plural version of the unit name, e.g. 'meters'
129 * @param abbreviation - abbreviated unit name, e.g. 'm'
130 * @param definition - the variadic parameter is used for the definition of the unit
131 * (e.g. `unit<std::ratio<1>, units::category::length_unit>`)
132 * @note a variadic template is used for the definition to allow templates with
133 * commas to be easily expanded. All the variadic 'arguments' should together
134 * comprise the unit definition.
135 */
136#define UNIT_ADD_UNIT_TAGS(namespaceName,nameSingular, namePlural, abbreviation, /*definition*/...)\
137 namespace namespaceName\
138 {\
139 /** @name Units (full names plural) */ /** @{ */ typedef __VA_ARGS__ namePlural; /** @} */\
140 /** @name Units (full names singular) */ /** @{ */ typedef namePlural nameSingular; /** @} */\
141 /** @name Units (abbreviated) */ /** @{ */ typedef namePlural abbreviation; /** @} */\
142 }
143
144/**
145 * @def UNIT_ADD_UNIT_DEFINITION(namespaceName,nameSingular)
146 * @brief Macro for generating the boiler-plate code for the unit_t type definition.
147 * @details The macro generates the definition of the unit container types, e.g. `meter_t`
148 * @param namespaceName namespace in which the new units will be encapsulated.
149 * @param nameSingular singular version of the unit name, e.g. 'meter'
150 */
151#define UNIT_ADD_UNIT_DEFINITION(namespaceName,nameSingular)\
152 namespace namespaceName\
153 {\
154 /** @name Unit Containers */ /** @{ */ typedef unit_t<nameSingular> nameSingular ## _t; /** @} */\
155 }
156
157/**
158 * @def UNIT_ADD_CUSTOM_TYPE_UNIT_DEFINITION(namespaceName,nameSingular,underlyingType)
159 * @brief Macro for generating the boiler-plate code for a unit_t type definition with a non-default underlying type.
160 * @details The macro generates the definition of the unit container types, e.g. `meter_t`
161 * @param namespaceName namespace in which the new units will be encapsulated.
162 * @param nameSingular singular version of the unit name, e.g. 'meter'
163 * @param underlyingType the underlying type
164 */
165#define UNIT_ADD_CUSTOM_TYPE_UNIT_DEFINITION(namespaceName,nameSingular, underlyingType)\
166 namespace namespaceName\
167 {\
168 /** @name Unit Containers */ /** @{ */ typedef unit_t<nameSingular,underlyingType> nameSingular ## _t; /** @} */\
169 }
170/**
171 * @def UNIT_ADD_IO(namespaceName,nameSingular, abbreviation)
172 * @brief Macro for generating the boiler-plate code needed for I/O for a new unit.
173 * @details The macro generates the code to insert units into an ostream. It
174 * prints both the value and abbreviation of the unit when invoked.
175 * @param namespaceName namespace in which the new units will be encapsulated.
176 * @param nameSingular singular version of the unit name, e.g. 'meter'
177 * @param abbrev - abbreviated unit name, e.g. 'm'
178 * @note When UNIT_LIB_ENABLE_IOSTREAM isn't defined, the macro does not generate any code
179 */
180#if __has_include(<fmt/format.h>) && !defined(UNIT_LIB_DISABLE_FMT)
181 #define UNIT_ADD_IO(namespaceName, nameSingular, abbrev)\
182 }\
183 template <>\
184 struct fmt::formatter<units::namespaceName::nameSingular ## _t> \
185 : fmt::formatter<double> \
186 {\
187 template <typename FmtContext>\
188 auto format(\
189 const units::namespaceName::nameSingular ## _t& obj,\
190 FmtContext& ctx) const\
191 {\
192 auto out = ctx.out();\
193 out = fmt::formatter<double>::format(obj(), ctx);\
194 return fmt::format_to(out, " " #abbrev);\
195 }\
196 };\
197 namespace units\
198 {\
199 namespace namespaceName\
200 {\
201 inline std::string to_string(const nameSingular ## _t& obj)\
202 {\
203 return units::detail::to_string(obj()) + std::string(" "#abbrev);\
204 }\
205 }
206#endif
207#if defined(UNIT_LIB_ENABLE_IOSTREAM)
208 #define UNIT_ADD_IO(namespaceName, nameSingular, abbrev)\
209 namespace namespaceName\
210 {\
211 inline std::ostream& operator<<(std::ostream& os, const nameSingular ## _t& obj) \
212 {\
213 os << obj() << " "#abbrev; return os; \
214 }\
215 inline std::string to_string(const nameSingular ## _t& obj)\
216 {\
217 return units::detail::to_string(obj()) + std::string(" "#abbrev);\
218 }\
219 }
220#endif
221
222 /**
223 * @def UNIT_ADD_NAME(namespaceName,nameSingular,abbreviation)
224 * @brief Macro for generating constexpr names/abbreviations for units.
225 * @details The macro generates names for units. E.g. name() of 1_m would be "meter", and
226 * abbreviation would be "m".
227 * @param namespaceName namespace in which the new units will be encapsulated. All literal values
228 * are placed in the `units::literals` namespace.
229 * @param nameSingular singular version of the unit name, e.g. 'meter'
230 * @param abbreviation - abbreviated unit name, e.g. 'm'
231 */
232#define UNIT_ADD_NAME(namespaceName, nameSingular, abbrev)\
233template<> inline constexpr const char* name(const namespaceName::nameSingular ## _t&)\
234{\
235 return #nameSingular;\
236}\
237template<> inline constexpr const char* abbreviation(const namespaceName::nameSingular ## _t&)\
238{\
239 return #abbrev;\
240}
241
242/**
243 * @def UNIT_ADD_LITERALS(namespaceName,nameSingular,abbreviation)
244 * @brief Macro for generating user-defined literals for units.
245 * @details The macro generates user-defined literals for units. A literal suffix is created
246 * using the abbreviation (e.g. `10.0_m`).
247 * @param namespaceName namespace in which the new units will be encapsulated. All literal values
248 * are placed in the `units::literals` namespace.
249 * @param nameSingular singular version of the unit name, e.g. 'meter'
250 * @param abbreviation - abbreviated unit name, e.g. 'm'
251 * @note When UNIT_HAS_LITERAL_SUPPORT is not defined, the macro does not generate any code
252 */
253#if defined(UNIT_HAS_LITERAL_SUPPORT)
254 #define UNIT_ADD_LITERALS(namespaceName, nameSingular, abbreviation)\
255 namespace literals\
256 {\
257 inline constexpr namespaceName::nameSingular ## _t operator""_ ## abbreviation(long double d)\
258 {\
259 return namespaceName::nameSingular ## _t(static_cast<namespaceName::nameSingular ## _t::underlying_type>(d));\
260 }\
261 inline constexpr namespaceName::nameSingular ## _t operator""_ ## abbreviation (unsigned long long d)\
262 {\
263 return namespaceName::nameSingular ## _t(static_cast<namespaceName::nameSingular ## _t::underlying_type>(d));\
264 }\
265 }
266#else
267 #define UNIT_ADD_LITERALS(namespaceName, nameSingular, abbreviation)
268#endif
269
270/**
271 * @def UNIT_ADD(namespaceName,nameSingular, namePlural, abbreviation, definition)
272 * @brief Macro for generating the boiler-plate code needed for a new unit.
273 * @details The macro generates singular, plural, and abbreviated forms
274 * of the unit definition (e.g. `meter`, `meters`, and `m`), as well as the
275 * appropriately named unit container (e.g. `meter_t`). A literal suffix is created
276 * using the abbreviation (e.g. `10.0_m`). It also defines a class-specific
277 * cout function which prints both the value and abbreviation of the unit when invoked.
278 * @param namespaceName namespace in which the new units will be encapsulated. All literal values
279 * are placed in the `units::literals` namespace.
280 * @param nameSingular singular version of the unit name, e.g. 'meter'
281 * @param namePlural - plural version of the unit name, e.g. 'meters'
282 * @param abbreviation - abbreviated unit name, e.g. 'm'
283 * @param definition - the variadic parameter is used for the definition of the unit
284 * (e.g. `unit<std::ratio<1>, units::category::length_unit>`)
285 * @note a variadic template is used for the definition to allow templates with
286 * commas to be easily expanded. All the variadic 'arguments' should together
287 * comprise the unit definition.
288 */
289#define UNIT_ADD(namespaceName, nameSingular, namePlural, abbreviation, /*definition*/...)\
290 UNIT_ADD_UNIT_TAGS(namespaceName,nameSingular, namePlural, abbreviation, __VA_ARGS__)\
291 UNIT_ADD_UNIT_DEFINITION(namespaceName,nameSingular)\
292 UNIT_ADD_NAME(namespaceName,nameSingular, abbreviation)\
293 UNIT_ADD_IO(namespaceName,nameSingular, abbreviation)\
294 UNIT_ADD_LITERALS(namespaceName,nameSingular, abbreviation)
295
296/**
297 * @def UNIT_ADD_WITH_CUSTOM_TYPE(namespaceName,nameSingular, namePlural, abbreviation, underlyingType, definition)
298 * @brief Macro for generating the boiler-plate code needed for a new unit with a non-default underlying type.
299 * @details The macro generates singular, plural, and abbreviated forms
300 * of the unit definition (e.g. `meter`, `meters`, and `m`), as well as the
301 * appropriately named unit container (e.g. `meter_t`). A literal suffix is created
302 * using the abbreviation (e.g. `10.0_m`). It also defines a class-specific
303 * cout function which prints both the value and abbreviation of the unit when invoked.
304 * @param namespaceName namespace in which the new units will be encapsulated. All literal values
305 * are placed in the `units::literals` namespace.
306 * @param nameSingular singular version of the unit name, e.g. 'meter'
307 * @param namePlural - plural version of the unit name, e.g. 'meters'
308 * @param abbreviation - abbreviated unit name, e.g. 'm'
309 * @param underlyingType - the underlying type, e.g. 'int' or 'float'
310 * @param definition - the variadic parameter is used for the definition of the unit
311 * (e.g. `unit<std::ratio<1>, units::category::length_unit>`)
312 * @note a variadic template is used for the definition to allow templates with
313 * commas to be easily expanded. All the variadic 'arguments' should together
314 * comprise the unit definition.
315 */
316#define UNIT_ADD_WITH_CUSTOM_TYPE(namespaceName, nameSingular, namePlural, abbreviation, underlyingType, /*definition*/...)\
317 UNIT_ADD_UNIT_TAGS(namespaceName,nameSingular, namePlural, abbreviation, __VA_ARGS__)\
318 UNIT_ADD_CUSTOM_TYPE_UNIT_DEFINITION(namespaceName,nameSingular,underlyingType)\
319 UNIT_ADD_IO(namespaceName,nameSingular, abbreviation)\
320 UNIT_ADD_LITERALS(namespaceName,nameSingular, abbreviation)
321
322/**
323 * @def UNIT_ADD_DECIBEL(namespaceName, nameSingular, abbreviation)
324 * @brief Macro to create decibel container and literals for an existing unit type.
325 * @details This macro generates the decibel unit container, cout overload, and literal definitions.
326 * @param namespaceName namespace in which the new units will be encapsulated. All literal values
327 * are placed in the `units::literals` namespace.
328 * @param nameSingular singular version of the base unit name, e.g. 'watt'
329 * @param abbreviation - abbreviated decibel unit name, e.g. 'dBW'
330 */
331#define UNIT_ADD_DECIBEL(namespaceName, nameSingular, abbreviation)\
332 namespace namespaceName\
333 {\
334 /** @name Unit Containers */ /** @{ */ typedef unit_t<nameSingular, UNIT_LIB_DEFAULT_TYPE, units::decibel_scale> abbreviation ## _t; /** @} */\
335 }\
336 UNIT_ADD_IO(namespaceName, abbreviation, abbreviation)\
337 UNIT_ADD_LITERALS(namespaceName, abbreviation, abbreviation)
338
339/**
340 * @def UNIT_ADD_CATEGORY_TRAIT(unitCategory, baseUnit)
341 * @brief Macro to create the `is_category_unit` type trait.
342 * @details This trait allows users to test whether a given type matches
343 * an intended category. This macro comprises all the boiler-plate
344 * code necessary to do so.
345 * @param unitCategory The name of the category of unit, e.g. length or mass.
346 */
347
348#define UNIT_ADD_CATEGORY_TRAIT_DETAIL(unitCategory)\
349 namespace traits\
350 {\
351 /** @cond */\
352 namespace detail\
353 {\
354 template<typename T> struct is_ ## unitCategory ## _unit_impl : std::false_type {};\
355 template<typename C, typename U, typename P, typename T>\
356 struct is_ ## unitCategory ## _unit_impl<units::unit<C, U, P, T>> : std::is_same<units::traits::base_unit_of<typename units::traits::unit_traits<units::unit<C, U, P, T>>::base_unit_type>, units::category::unitCategory ## _unit>::type {};\
357 template<typename U, typename S, template<typename> class N>\
358 struct is_ ## unitCategory ## _unit_impl<units::unit_t<U, S, N>> : std::is_same<units::traits::base_unit_of<typename units::traits::unit_t_traits<units::unit_t<U, S, N>>::unit_type>, units::category::unitCategory ## _unit>::type {};\
359 }\
360 /** @endcond */\
361 }
362
363#define UNIT_ADD_IS_UNIT_CATEGORY_TRAIT(unitCategory)\
364 namespace traits\
365 {\
366 template<typename... T> struct is_ ## unitCategory ## _unit : std::integral_constant<bool, units::all_true<units::traits::detail::is_ ## unitCategory ## _unit_impl<std::decay_t<T>>::value...>::value> {};\
367 template<typename... T> inline constexpr bool is_ ## unitCategory ## _unit_v = is_ ## unitCategory ## _unit<T...>::value;\
368 }\
369 template <typename T>\
370 concept unitCategory ## _unit = traits::is_ ## unitCategory ## _unit_v<T>;
371
372#define UNIT_ADD_CATEGORY_TRAIT(unitCategory)\
373 UNIT_ADD_CATEGORY_TRAIT_DETAIL(unitCategory)\
374 /** @ingroup TypeTraits*/\
375 /** @brief Trait which tests whether a type represents a unit of unitCategory*/\
376 /** @details Inherits from `std::true_type` or `std::false_type`. Use `is_ ## unitCategory ## _unit<T>::value` to test the unit represents a unitCategory quantity.*/\
377 /** @tparam T one or more types to test*/\
378 UNIT_ADD_IS_UNIT_CATEGORY_TRAIT(unitCategory)
379
380/**
381 * @def UNIT_ADD_WITH_METRIC_PREFIXES(nameSingular, namePlural, abbreviation, definition)
382 * @brief Macro for generating the boiler-plate code needed for a new unit, including its metric
383 * prefixes from femto to peta.
384 * @details See UNIT_ADD. In addition to generating the unit definition and containers '(e.g. `meters` and 'meter_t',
385 * it also creates corresponding units with metric suffixes such as `millimeters`, and `millimeter_t`), as well as the
386 * literal suffixes (e.g. `10.0_mm`).
387 * @param namespaceName namespace in which the new units will be encapsulated. All literal values
388 * are placed in the `units::literals` namespace.
389 * @param nameSingular singular version of the unit name, e.g. 'meter'
390 * @param namePlural - plural version of the unit name, e.g. 'meters'
391 * @param abbreviation - abbreviated unit name, e.g. 'm'
392 * @param definition - the variadic parameter is used for the definition of the unit
393 * (e.g. `unit<std::ratio<1>, units::category::length_unit>`)
394 * @note a variadic template is used for the definition to allow templates with
395 * commas to be easily expanded. All the variadic 'arguments' should together
396 * comprise the unit definition.
397 */
398#define UNIT_ADD_WITH_METRIC_PREFIXES(namespaceName, nameSingular, namePlural, abbreviation, /*definition*/...)\
399 UNIT_ADD(namespaceName, nameSingular, namePlural, abbreviation, __VA_ARGS__)\
400 UNIT_ADD(namespaceName, femto ## nameSingular, femto ## namePlural, f ## abbreviation, femto<namePlural>)\
401 UNIT_ADD(namespaceName, pico ## nameSingular, pico ## namePlural, p ## abbreviation, pico<namePlural>)\
402 UNIT_ADD(namespaceName, nano ## nameSingular, nano ## namePlural, n ## abbreviation, nano<namePlural>)\
403 UNIT_ADD(namespaceName, micro ## nameSingular, micro ## namePlural, u ## abbreviation, micro<namePlural>)\
404 UNIT_ADD(namespaceName, milli ## nameSingular, milli ## namePlural, m ## abbreviation, milli<namePlural>)\
405 UNIT_ADD(namespaceName, centi ## nameSingular, centi ## namePlural, c ## abbreviation, centi<namePlural>)\
406 UNIT_ADD(namespaceName, deci ## nameSingular, deci ## namePlural, d ## abbreviation, deci<namePlural>)\
407 UNIT_ADD(namespaceName, deca ## nameSingular, deca ## namePlural, da ## abbreviation, deca<namePlural>)\
408 UNIT_ADD(namespaceName, hecto ## nameSingular, hecto ## namePlural, h ## abbreviation, hecto<namePlural>)\
409 UNIT_ADD(namespaceName, kilo ## nameSingular, kilo ## namePlural, k ## abbreviation, kilo<namePlural>)\
410 UNIT_ADD(namespaceName, mega ## nameSingular, mega ## namePlural, M ## abbreviation, mega<namePlural>)\
411 UNIT_ADD(namespaceName, giga ## nameSingular, giga ## namePlural, G ## abbreviation, giga<namePlural>)\
412 UNIT_ADD(namespaceName, tera ## nameSingular, tera ## namePlural, T ## abbreviation, tera<namePlural>)\
413 UNIT_ADD(namespaceName, peta ## nameSingular, peta ## namePlural, P ## abbreviation, peta<namePlural>)\
414
415 /**
416 * @def UNIT_ADD_WITH_METRIC_AND_BINARY_PREFIXES(nameSingular, namePlural, abbreviation, definition)
417 * @brief Macro for generating the boiler-plate code needed for a new unit, including its metric
418 * prefixes from femto to peta, and binary prefixes from kibi to exbi.
419 * @details See UNIT_ADD. In addition to generating the unit definition and containers '(e.g. `bytes` and 'byte_t',
420 * it also creates corresponding units with metric suffixes such as `millimeters`, and `millimeter_t`), as well as the
421 * literal suffixes (e.g. `10.0_B`).
422 * @param namespaceName namespace in which the new units will be encapsulated. All literal values
423 * are placed in the `units::literals` namespace.
424 * @param nameSingular singular version of the unit name, e.g. 'byte'
425 * @param namePlural - plural version of the unit name, e.g. 'bytes'
426 * @param abbreviation - abbreviated unit name, e.g. 'B'
427 * @param definition - the variadic parameter is used for the definition of the unit
428 * (e.g. `unit<std::ratio<1>, units::category::data_unit>`)
429 * @note a variadic template is used for the definition to allow templates with
430 * commas to be easily expanded. All the variadic 'arguments' should together
431 * comprise the unit definition.
432 */
433#define UNIT_ADD_WITH_METRIC_AND_BINARY_PREFIXES(namespaceName, nameSingular, namePlural, abbreviation, /*definition*/...)\
434 UNIT_ADD_WITH_METRIC_PREFIXES(namespaceName, nameSingular, namePlural, abbreviation, __VA_ARGS__)\
435 UNIT_ADD(namespaceName, kibi ## nameSingular, kibi ## namePlural, Ki ## abbreviation, kibi<namePlural>)\
436 UNIT_ADD(namespaceName, mebi ## nameSingular, mebi ## namePlural, Mi ## abbreviation, mebi<namePlural>)\
437 UNIT_ADD(namespaceName, gibi ## nameSingular, gibi ## namePlural, Gi ## abbreviation, gibi<namePlural>)\
438 UNIT_ADD(namespaceName, tebi ## nameSingular, tebi ## namePlural, Ti ## abbreviation, tebi<namePlural>)\
439 UNIT_ADD(namespaceName, pebi ## nameSingular, pebi ## namePlural, Pi ## abbreviation, pebi<namePlural>)\
440 UNIT_ADD(namespaceName, exbi ## nameSingular, exbi ## namePlural, Ei ## abbreviation, exbi<namePlural>)
441
442//--------------------
443// UNITS NAMESPACE
444//--------------------
445
446/**
447 * @namespace units
448 * @brief Unit Conversion Library namespace
449 */
450namespace units
451{
452 //----------------------------------
453 // DOXYGEN
454 //----------------------------------
455
456 /**
457 * @defgroup Units Unit API
458 */
459
460 /**
461 * @defgroup UnitContainers Unit Containers
462 * @ingroup Units
463 * @brief Defines a series of classes which contain dimensioned values. Unit containers
464 * store a value, and support various arithmetic operations.
465 */
466
467 /**
468 * @defgroup UnitTypes Unit Types
469 * @ingroup Units
470 * @brief Defines a series of classes which represent units. These types are tags used by
471 * the conversion function, to create compound units, or to create `unit_t` types.
472 * By themselves, they are not containers and have no stored value.
473 */
474
475 /**
476 * @defgroup UnitManipulators Unit Manipulators
477 * @ingroup Units
478 * @brief Defines a series of classes used to manipulate unit types, such as `inverse<>`, `squared<>`, and metric prefixes.
479 * Unit manipulators can be chained together, e.g. `inverse<squared<pico<time::seconds>>>` to
480 * represent picoseconds^-2.
481 */
482
483 /**
484 * @defgroup CompileTimeUnitManipulators Compile-time Unit Manipulators
485 * @ingroup Units
486 * @brief Defines a series of classes used to manipulate `unit_value_t` types at compile-time, such as `unit_value_add<>`, `unit_value_sqrt<>`, etc.
487 * Compile-time manipulators can be chained together, e.g. `unit_value_sqrt<unit_value_add<unit_value_power<a, 2>, unit_value_power<b, 2>>>` to
488 * represent `c = sqrt(a^2 + b^2).
489 */
490
491 /**
492 * @defgroup UnitMath Unit Math
493 * @ingroup Units
494 * @brief Defines a collection of unit-enabled, strongly-typed versions of `<cmath>` functions.
495 * @details Includes most c++11 extensions.
496 */
497
498 /**
499 * @defgroup Conversion Explicit Conversion
500 * @ingroup Units
501 * @brief Functions used to convert values of one logical type to another.
502 */
503
504 /**
505 * @defgroup TypeTraits Type Traits
506 * @ingroup Units
507 * @brief Defines a series of classes to obtain unit type information at compile-time.
508 */
509
510 //------------------------------
511 // FORWARD DECLARATIONS
512 //------------------------------
513
514 /** @cond */ // DOXYGEN IGNORE
515 namespace constants
516 {
517 namespace detail
518 {
519 static constexpr const UNIT_LIB_DEFAULT_TYPE PI_VAL = 3.14159265358979323846264338327950288419716939937510;
520 }
521 }
522 /** @endcond */ // END DOXYGEN IGNORE
523
524 //------------------------------
525 // RATIO TRAITS
526 //------------------------------
527
528 /**
529 * @ingroup TypeTraits
530 * @{
531 */
532
533 /** @cond */ // DOXYGEN IGNORE
534 namespace detail
535 {
536 /// has_num implementation.
537 template<class T>
538 struct has_num_impl
539 {
540 template<class U>
541 static constexpr auto test(U*)->std::is_integral<decltype(U::num)> {return std::is_integral<decltype(U::num)>{}; }
542 template<typename>
543 static constexpr std::false_type test(...) { return std::false_type{}; }
544
545 using type = decltype(test<T>(0));
546 };
547 }
548
549 /**
550 * @brief Trait which checks for the existence of a static numerator.
551 * @details Inherits from `std::true_type` or `std::false_type`. Use `has_num<T>::value` to test
552 * whether `class T` has a numerator static member.
553 */
554 template<class T>
555 struct has_num : units::detail::has_num_impl<T>::type {};
556
557 namespace detail
558 {
559 /// has_den implementation.
560 template<class T>
561 struct has_den_impl
562 {
563 template<class U>
564 static constexpr auto test(U*)->std::is_integral<decltype(U::den)> { return std::is_integral<decltype(U::den)>{}; }
565 template<typename>
566 static constexpr std::false_type test(...) { return std::false_type{}; }
567
568 using type = decltype(test<T>(0));
569 };
570 }
571
572 /**
573 * @brief Trait which checks for the existence of a static denominator.
574 * @details Inherits from `std::true_type` or `std::false_type`. Use `has_den<T>::value` to test
575 * whether `class T` has a denominator static member.
576 */
577 template<class T>
578 struct has_den : units::detail::has_den_impl<T>::type {};
579
580 /** @endcond */ // END DOXYGEN IGNORE
581
582 namespace traits
583 {
584 /**
585 * @brief Trait that tests whether a type represents a std::ratio.
586 * @details Inherits from `std::true_type` or `std::false_type`. Use `is_ratio<T>::value` to test
587 * whether `class T` implements a std::ratio.
588 */
589 template<class T>
590 struct is_ratio : std::integral_constant<bool,
591 has_num<T>::value &&
592 has_den<T>::value>
593 {};
594 template<class T>
595 inline constexpr bool is_ratio_v = is_ratio<T>::value;
596 }
597
598 //------------------------------
599 // UNIT TRAITS
600 //------------------------------
601
602 /** @cond */ // DOXYGEN IGNORE
603 /**
604 * @brief void type.
605 * @details Helper class for creating type traits.
606 */
607 template<class ...>
608 struct void_t { typedef void type; };
609
610 /**
611 * @brief parameter pack for boolean arguments.
612 */
613 template<bool...> struct bool_pack {};
614
615 /**
616 * @brief Trait which tests that a set of other traits are all true.
617 */
618 template<bool... Args>
619 struct all_true : std::is_same<units::bool_pack<true, Args...>, units::bool_pack<Args..., true>> {};
620 template<bool... Args>
621 inline constexpr bool all_true_t_v = all_true<Args...>::type::value;
622 /** @endcond */ // DOXYGEN IGNORE
623
624 /**
625 * @brief namespace representing type traits which can access the properties of types provided by the units library.
626 */
627 namespace traits
628 {
629#ifdef FOR_DOXYGEN_PURPOSES_ONLY
630 /**
631 * @ingroup TypeTraits
632 * @brief Traits class defining the properties of units.
633 * @details The units library determines certain properties of the units passed to
634 * them and what they represent by using the members of the corresponding
635 * unit_traits instantiation.
636 */
637 template<class T>
638 struct unit_traits
639 {
640 typedef typename T::base_unit_type base_unit_type; ///< Unit type that the unit was derived from. May be a `base_unit` or another `unit`. Use the `base_unit_of` trait to find the SI base unit type. This will be `void` if type `T` is not a unit.
641 typedef typename T::conversion_ratio conversion_ratio; ///< `std::ratio` representing the conversion factor to the `base_unit_type`. This will be `void` if type `T` is not a unit.
642 typedef typename T::pi_exponent_ratio pi_exponent_ratio; ///< `std::ratio` representing the exponent of pi to be used in the conversion. This will be `void` if type `T` is not a unit.
643 typedef typename T::translation_ratio translation_ratio; ///< `std::ratio` representing a datum translation to the base unit (i.e. degrees C to degrees F conversion). This will be `void` if type `T` is not a unit.
644 };
645#endif
646 /** @cond */ // DOXYGEN IGNORE
647 /**
648 * @brief unit traits implementation for classes which are not units.
649 */
650 template<class T, typename = void>
651 struct unit_traits
652 {
653 typedef void base_unit_type;
654 typedef void conversion_ratio;
655 typedef void pi_exponent_ratio;
656 typedef void translation_ratio;
657 };
658
659 template<class T>
660 struct unit_traits
661 <T, typename void_t<
662 typename T::base_unit_type,
663 typename T::conversion_ratio,
664 typename T::pi_exponent_ratio,
665 typename T::translation_ratio>::type>
666 {
667 typedef typename T::base_unit_type base_unit_type; ///< Unit type that the unit was derived from. May be a `base_unit` or another `unit`. Use the `base_unit_of` trait to find the SI base unit type. This will be `void` if type `T` is not a unit.
668 typedef typename T::conversion_ratio conversion_ratio; ///< `std::ratio` representing the conversion factor to the `base_unit_type`. This will be `void` if type `T` is not a unit.
669 typedef typename T::pi_exponent_ratio pi_exponent_ratio; ///< `std::ratio` representing the exponent of pi to be used in the conversion. This will be `void` if type `T` is not a unit.
670 typedef typename T::translation_ratio translation_ratio; ///< `std::ratio` representing a datum translation to the base unit (i.e. degrees C to degrees F conversion). This will be `void` if type `T` is not a unit.
671 };
672 /** @endcond */ // END DOXYGEN IGNORE
673 }
674
675 /** @cond */ // DOXYGEN IGNORE
676 namespace detail
677 {
678 /**
679 * @brief helper type to identify base units.
680 * @details A non-templated base class for `base_unit` which enables RTTI testing.
681 */
682 struct _base_unit_t {};
683 }
684 /** @endcond */ // END DOXYGEN IGNORE
685
686 namespace traits
687 {
688 /**
689 * @ingroup TypeTraits
690 * @brief Trait which tests if a class is a `base_unit` type.
691 * @details Inherits from `std::true_type` or `std::false_type`. Use `is_base_unit<T>::value` to test
692 * whether `class T` implements a `base_unit`.
693 */
694 template<class T>
695 struct is_base_unit : std::is_base_of<units::detail::_base_unit_t, T> {};
696 }
697
698 /** @cond */ // DOXYGEN IGNORE
699 namespace detail
700 {
701 /**
702 * @brief helper type to identify units.
703 * @details A non-templated base class for `unit` which enables RTTI testing.
704 */
705 struct _unit {};
706
707 template<std::intmax_t Num, std::intmax_t Den = 1>
708 using meter_ratio = std::ratio<Num, Den>;
709 }
710 /** @endcond */ // END DOXYGEN IGNORE
711
712 namespace traits
713 {
714 /**
715 * @ingroup TypeTraits
716 * @brief Traits which tests if a class is a `unit`
717 * @details Inherits from `std::true_type` or `std::false_type`. Use `is_unit<T>::value` to test
718 * whether `class T` implements a `unit`.
719 */
720 template<class T>
721 struct is_unit : std::is_base_of<units::detail::_unit, T>::type {};
722 template<class T>
723 inline constexpr bool is_unit_v = is_unit<T>::value;
724 }
725
726 /** @} */ // end of TypeTraits
727
728 //------------------------------
729 // BASE UNIT CLASS
730 //------------------------------
731
732 /**
733 * @ingroup UnitTypes
734 * @brief Class representing SI base unit types.
735 * @details Base units are represented by a combination of `std::ratio` template parameters, each
736 * describing the exponent of the type of unit they represent. Example: meters per second
737 * would be described by a +1 exponent for meters, and a -1 exponent for seconds, thus:
738 * `base_unit<std::ratio<1>, std::ratio<0>, std::ratio<-1>>`
739 * @tparam Meter `std::ratio` representing the exponent value for meters.
740 * @tparam Kilogram `std::ratio` representing the exponent value for kilograms.
741 * @tparam Second `std::ratio` representing the exponent value for seconds.
742 * @tparam Radian `std::ratio` representing the exponent value for radians. Although radians are not SI base units, they are included because radians are described by the SI as m * m^-1, which would make them indistinguishable from scalars.
743 * @tparam Ampere `std::ratio` representing the exponent value for amperes.
744 * @tparam Kelvin `std::ratio` representing the exponent value for Kelvin.
745 * @tparam Mole `std::ratio` representing the exponent value for moles.
746 * @tparam Candela `std::ratio` representing the exponent value for candelas.
747 * @tparam Byte `std::ratio` representing the exponent value for bytes.
748 * @sa category for type aliases for SI base_unit types.
749 */
750 template<class Meter = detail::meter_ratio<0>,
751 class Kilogram = std::ratio<0>,
752 class Second = std::ratio<0>,
753 class Radian = std::ratio<0>,
754 class Ampere = std::ratio<0>,
755 class Kelvin = std::ratio<0>,
756 class Mole = std::ratio<0>,
757 class Candela = std::ratio<0>,
758 class Byte = std::ratio<0>>
759 struct base_unit : units::detail::_base_unit_t
760 {
761 static_assert(traits::is_ratio<Meter>::value, "Template parameter `Meter` must be a `std::ratio` representing the exponent of meters the unit has");
762 static_assert(traits::is_ratio<Kilogram>::value, "Template parameter `Kilogram` must be a `std::ratio` representing the exponent of kilograms the unit has");
763 static_assert(traits::is_ratio<Second>::value, "Template parameter `Second` must be a `std::ratio` representing the exponent of seconds the unit has");
764 static_assert(traits::is_ratio<Ampere>::value, "Template parameter `Ampere` must be a `std::ratio` representing the exponent of amperes the unit has");
765 static_assert(traits::is_ratio<Kelvin>::value, "Template parameter `Kelvin` must be a `std::ratio` representing the exponent of kelvin the unit has");
766 static_assert(traits::is_ratio<Candela>::value, "Template parameter `Candela` must be a `std::ratio` representing the exponent of candelas the unit has");
767 static_assert(traits::is_ratio<Mole>::value, "Template parameter `Mole` must be a `std::ratio` representing the exponent of moles the unit has");
768 static_assert(traits::is_ratio<Radian>::value, "Template parameter `Radian` must be a `std::ratio` representing the exponent of radians the unit has");
769 static_assert(traits::is_ratio<Byte>::value, "Template parameter `Byte` must be a `std::ratio` representing the exponent of bytes the unit has");
770
771 typedef Meter meter_ratio;
772 typedef Kilogram kilogram_ratio;
773 typedef Second second_ratio;
774 typedef Radian radian_ratio;
775 typedef Ampere ampere_ratio;
776 typedef Kelvin kelvin_ratio;
777 typedef Mole mole_ratio;
778 typedef Candela candela_ratio;
779 typedef Byte byte_ratio;
780 };
781
782 //------------------------------
783 // UNIT CATEGORIES
784 //------------------------------
785
786 /**
787 * @brief namespace representing the implemented base and derived unit types. These will not generally be needed by library users.
788 * @sa base_unit for the definition of the category parameters.
789 */
790 namespace category
791 {
792 // SCALAR (DIMENSIONLESS) TYPES
793 typedef base_unit<> scalar_unit; ///< Represents a quantity with no dimension.
794 typedef base_unit<> dimensionless_unit; ///< Represents a quantity with no dimension.
795
796 // SI BASE UNIT TYPES
797 // METERS KILOGRAMS SECONDS RADIANS AMPERES KELVIN MOLE CANDELA BYTE --- CATEGORY
798 typedef base_unit<detail::meter_ratio<1>> length_unit; ///< Represents an SI base unit of length
799 typedef base_unit<detail::meter_ratio<0>, std::ratio<1>> mass_unit; ///< Represents an SI base unit of mass
800 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<1>> time_unit; ///< Represents an SI base unit of time
801 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> angle_unit; ///< Represents an SI base unit of angle
802 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> current_unit; ///< Represents an SI base unit of current
803 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> temperature_unit; ///< Represents an SI base unit of temperature
804 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> substance_unit; ///< Represents an SI base unit of amount of substance
805 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> luminous_intensity_unit; ///< Represents an SI base unit of luminous intensity
806
807 // SI DERIVED UNIT TYPES
808 // METERS KILOGRAMS SECONDS RADIANS AMPERES KELVIN MOLE CANDELA BYTE --- CATEGORY
809 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<2>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>> solid_angle_unit; ///< Represents an SI derived unit of solid angle
810 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<-1>> frequency_unit; ///< Represents an SI derived unit of frequency
811 typedef base_unit<detail::meter_ratio<1>, std::ratio<0>, std::ratio<-1>> velocity_unit; ///< Represents an SI derived unit of velocity
812 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<-1>, std::ratio<1>> angular_velocity_unit; ///< Represents an SI derived unit of angular velocity
813 typedef base_unit<detail::meter_ratio<1>, std::ratio<0>, std::ratio<-2>> acceleration_unit; ///< Represents an SI derived unit of acceleration
814 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<-2>, std::ratio<1>> angular_acceleration_unit; ///< Represents an SI derived unit of angular acceleration
815 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<-3>, std::ratio<1>> angular_jerk_unit; ///< Represents an SI derived unit of angular jerk
816 typedef base_unit<detail::meter_ratio<1>, std::ratio<1>, std::ratio<-2>> force_unit; ///< Represents an SI derived unit of force
817 typedef base_unit<detail::meter_ratio<-1>, std::ratio<1>, std::ratio<-2>> pressure_unit; ///< Represents an SI derived unit of pressure
818 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<1>, std::ratio<0>, std::ratio<1>> charge_unit; ///< Represents an SI derived unit of charge
819 typedef base_unit<detail::meter_ratio<2>, std::ratio<1>, std::ratio<-2>> energy_unit; ///< Represents an SI derived unit of energy
820 typedef base_unit<detail::meter_ratio<2>, std::ratio<1>, std::ratio<-3>> power_unit; ///< Represents an SI derived unit of power
821 typedef base_unit<detail::meter_ratio<2>, std::ratio<1>, std::ratio<-3>, std::ratio<0>, std::ratio<-1>> voltage_unit; ///< Represents an SI derived unit of voltage
822 typedef base_unit<detail::meter_ratio<-2>, std::ratio<-1>, std::ratio<4>, std::ratio<0>, std::ratio<2>> capacitance_unit; ///< Represents an SI derived unit of capacitance
823 typedef base_unit<detail::meter_ratio<2>, std::ratio<1>, std::ratio<-3>, std::ratio<0>, std::ratio<-2>> impedance_unit; ///< Represents an SI derived unit of impedance
824 typedef base_unit<detail::meter_ratio<-2>, std::ratio<-1>, std::ratio<3>, std::ratio<0>, std::ratio<2>> conductance_unit; ///< Represents an SI derived unit of conductance
825 typedef base_unit<detail::meter_ratio<2>, std::ratio<1>, std::ratio<-2>, std::ratio<0>, std::ratio<-1>> magnetic_flux_unit; ///< Represents an SI derived unit of magnetic flux
826 typedef base_unit<detail::meter_ratio<0>, std::ratio<1>, std::ratio<-2>, std::ratio<0>, std::ratio<-1>> magnetic_field_strength_unit; ///< Represents an SI derived unit of magnetic field strength
827 typedef base_unit<detail::meter_ratio<2>, std::ratio<1>, std::ratio<-2>, std::ratio<0>, std::ratio<-2>> inductance_unit; ///< Represents an SI derived unit of inductance
828 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<2>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> luminous_flux_unit; ///< Represents an SI derived unit of luminous flux
829 typedef base_unit<detail::meter_ratio<-2>, std::ratio<0>, std::ratio<0>, std::ratio<2>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> illuminance_unit; ///< Represents an SI derived unit of illuminance
830 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<-1>> radioactivity_unit; ///< Represents an SI derived unit of radioactivity
831
832 // OTHER UNIT TYPES
833 // METERS KILOGRAMS SECONDS RADIANS AMPERES KELVIN MOLE CANDELA BYTE --- CATEGORY
834 typedef base_unit<detail::meter_ratio<2>, std::ratio<1>, std::ratio<-2>> torque_unit; ///< Represents an SI derived unit of torque
835 typedef base_unit<detail::meter_ratio<2>> area_unit; ///< Represents an SI derived unit of area
836 typedef base_unit<detail::meter_ratio<3>> volume_unit; ///< Represents an SI derived unit of volume
837 typedef base_unit<detail::meter_ratio<-3>, std::ratio<1>> density_unit; ///< Represents an SI derived unit of density
838 typedef base_unit<> concentration_unit; ///< Represents a unit of concentration
839 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> data_unit; ///< Represents a unit of data size
840 typedef base_unit<detail::meter_ratio<0>, std::ratio<0>, std::ratio<-1>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<1>> data_transfer_rate_unit; ///< Represents a unit of data transfer rate
841 }
842
843 //------------------------------
844 // UNIT CLASSES
845 //------------------------------
846
847 /** @cond */ // DOXYGEN IGNORE
848 /**
849 * @brief unit type template specialization for units derived from base units.
850 */
851 template <class, class, class, class> struct unit;
852 template<class Conversion, class... Exponents, class PiExponent, class Translation>
853 struct unit<Conversion, base_unit<Exponents...>, PiExponent, Translation> : units::detail::_unit
854 {
855 static_assert(traits::is_ratio<Conversion>::value, "Template parameter `Conversion` must be a `std::ratio` representing the conversion factor to `BaseUnit`.");
856 static_assert(traits::is_ratio<PiExponent>::value, "Template parameter `PiExponent` must be a `std::ratio` representing the exponents of Pi the unit has.");
857 static_assert(traits::is_ratio<Translation>::value, "Template parameter `Translation` must be a `std::ratio` representing an additive translation required by the unit conversion.");
858
859 typedef typename units::base_unit<Exponents...> base_unit_type;
860 typedef Conversion conversion_ratio;
861 typedef Translation translation_ratio;
862 typedef PiExponent pi_exponent_ratio;
863 };
864 /** @endcond */ // END DOXYGEN IGNORE
865
866 /**
867 * @brief Type representing an arbitrary unit.
868 * @ingroup UnitTypes
869 * @details `unit` types are used as tags for the `conversion` function. They are *not* containers
870 * (see `unit_t` for a container class). Each unit is defined by:
871 *
872 * - A `std::ratio` defining the conversion factor to the base unit type. (e.g. `std::ratio<1,12>` for inches to feet)
873 * - A base unit that the unit is derived from (or a unit category. Must be of type `unit` or `base_unit`)
874 * - An exponent representing factors of PI required by the conversion. (e.g. `std::ratio<-1>` for a radians to degrees conversion)
875 * - a ratio representing a datum translation required for the conversion (e.g. `std::ratio<32>` for a fahrenheit to celsius conversion)
876 *
877 * Typically, a specific unit, like `meters`, would be implemented as a type alias
878 * of `unit`, i.e. `using meters = unit<std::ratio<1>, units::category::length_unit`, or
879 * `using inches = unit<std::ratio<1,12>, feet>`.
880 * @tparam Conversion std::ratio representing scalar multiplication factor.
881 * @tparam BaseUnit Unit type which this unit is derived from. May be a `base_unit`, or another `unit`.
882 * @tparam PiExponent std::ratio representing the exponent of pi required by the conversion.
883 * @tparam Translation std::ratio representing any datum translation required by the conversion.
884 */
885 template<class Conversion, class BaseUnit, class PiExponent = std::ratio<0>, class Translation = std::ratio<0>>
886 struct unit : units::detail::_unit
887 {
888 static_assert(traits::is_unit<BaseUnit>::value, "Template parameter `BaseUnit` must be a `unit` type.");
889 static_assert(traits::is_ratio<Conversion>::value, "Template parameter `Conversion` must be a `std::ratio` representing the conversion factor to `BaseUnit`.");
890 static_assert(traits::is_ratio<PiExponent>::value, "Template parameter `PiExponent` must be a `std::ratio` representing the exponents of Pi the unit has.");
891
892 typedef typename units::traits::unit_traits<BaseUnit>::base_unit_type base_unit_type;
893 typedef typename std::ratio_multiply<typename BaseUnit::conversion_ratio, Conversion> conversion_ratio;
894 typedef typename std::ratio_add<typename BaseUnit::pi_exponent_ratio, PiExponent> pi_exponent_ratio;
895 typedef typename std::ratio_add<std::ratio_multiply<typename BaseUnit::conversion_ratio, Translation>, typename BaseUnit::translation_ratio> translation_ratio;
896 };
897
898 //------------------------------
899 // BASE UNIT MANIPULATORS
900 //------------------------------
901
902 /** @cond */ // DOXYGEN IGNORE
903 namespace detail
904 {
905 /**
906 * @brief base_unit_of trait implementation
907 * @details recursively seeks base_unit type that a unit is derived from. Since units can be
908 * derived from other units, the `base_unit_type` typedef may not represent this value.
909 */
910 template<class> struct base_unit_of_impl;
911 template<class Conversion, class BaseUnit, class PiExponent, class Translation>
912 struct base_unit_of_impl<unit<Conversion, BaseUnit, PiExponent, Translation>> : base_unit_of_impl<BaseUnit> {};
913 template<class... Exponents>
914 struct base_unit_of_impl<base_unit<Exponents...>>
915 {
916 typedef base_unit<Exponents...> type;
917 };
918 template<>
919 struct base_unit_of_impl<void>
920 {
921 typedef void type;
922 };
923 }
924 /** @endcond */ // END DOXYGEN IGNORE
925
926 namespace traits
927 {
928 /**
929 * @brief Trait which returns the `base_unit` type that a unit is originally derived from.
930 * @details Since units can be derived from other `unit` types in addition to `base_unit` types,
931 * the `base_unit_type` typedef will not always be a `base_unit` (or unit category).
932 * Since compatible
933 */
934 template<class U>
936 }
937
938 /** @cond */ // DOXYGEN IGNORE
939 namespace detail
940 {
941 /**
942 * @brief implementation of base_unit_multiply
943 * @details 'multiples' (adds exponent ratios of) two base unit types. Base units can be found
944 * using `base_unit_of`.
945 */
946 template<class, class> struct base_unit_multiply_impl;
947 template<class... Exponents1, class... Exponents2>
948 struct base_unit_multiply_impl<base_unit<Exponents1...>, base_unit<Exponents2...>> {
950 };
951
952 /**
953 * @brief represents type of two base units multiplied together
954 */
955 template<class U1, class U2>
956 using base_unit_multiply = typename base_unit_multiply_impl<U1, U2>::type;
957
958 /**
959 * @brief implementation of base_unit_divide
960 * @details 'dived' (subtracts exponent ratios of) two base unit types. Base units can be found
961 * using `base_unit_of`.
962 */
963 template<class, class> struct base_unit_divide_impl;
964 template<class... Exponents1, class... Exponents2>
965 struct base_unit_divide_impl<base_unit<Exponents1...>, base_unit<Exponents2...>> {
966 using type = base_unit<std::ratio_subtract<Exponents1, Exponents2>...>;
967 };
968
969 /**
970 * @brief represents the resulting type of `base_unit` U1 divided by U2.
971 */
972 template<class U1, class U2>
973 using base_unit_divide = typename base_unit_divide_impl<U1, U2>::type;
974
975 /**
976 * @brief implementation of inverse_base
977 * @details multiplies all `base_unit` exponent ratios by -1. The resulting type represents
978 * the inverse base unit of the given `base_unit` type.
979 */
980 template<class> struct inverse_base_impl;
981
982 template<class... Exponents>
983 struct inverse_base_impl<base_unit<Exponents...>> {
984 using type = base_unit<std::ratio_multiply<Exponents, std::ratio<-1>>...>;
985 };
986
987 /**
988 * @brief represent the inverse type of `class U`
989 * @details E.g. if `U` is `length_unit`, then `inverse<U>` will represent `length_unit^-1`.
990 */
991 template<class U> using inverse_base = typename inverse_base_impl<U>::type;
992
993 /**
994 * @brief implementation of `squared_base`
995 * @details multiplies all the exponent ratios of the given class by 2. The resulting type is
996 * equivalent to the given type squared.
997 */
998 template<class U> struct squared_base_impl;
999 template<class... Exponents>
1000 struct squared_base_impl<base_unit<Exponents...>> {
1001 using type = base_unit<std::ratio_multiply<Exponents, std::ratio<2>>...>;
1002 };
1003
1004 /**
1005 * @brief represents the type of a `base_unit` squared.
1006 * @details E.g. `squared<length_unit>` will represent `length_unit^2`.
1007 */
1008 template<class U> using squared_base = typename squared_base_impl<U>::type;
1009
1010 /**
1011 * @brief implementation of `cubed_base`
1012 * @details multiplies all the exponent ratios of the given class by 3. The resulting type is
1013 * equivalent to the given type cubed.
1014 */
1015 template<class U> struct cubed_base_impl;
1016 template<class... Exponents>
1017 struct cubed_base_impl<base_unit<Exponents...>> {
1018 using type = base_unit<std::ratio_multiply<Exponents, std::ratio<3>>...>;
1019 };
1020
1021 /**
1022 * @brief represents the type of a `base_unit` cubed.
1023 * @details E.g. `cubed<length_unit>` will represent `length_unit^3`.
1024 */
1025 template<class U> using cubed_base = typename cubed_base_impl<U>::type;
1026
1027 /**
1028 * @brief implementation of `sqrt_base`
1029 * @details divides all the exponent ratios of the given class by 2. The resulting type is
1030 * equivalent to the square root of the given type.
1031 */
1032 template<class U> struct sqrt_base_impl;
1033 template<class... Exponents>
1034 struct sqrt_base_impl<base_unit<Exponents...>> {
1035 using type = base_unit<std::ratio_divide<Exponents, std::ratio<2>>...>;
1036 };
1037
1038 /**
1039 * @brief represents the square-root type of a `base_unit`.
1040 * @details E.g. `sqrt<length_unit>` will represent `length_unit^(1/2)`.
1041 */
1042 template<class U> using sqrt_base = typename sqrt_base_impl<U>::type;
1043
1044 /**
1045 * @brief implementation of `cbrt_base`
1046 * @details divides all the exponent ratios of the given class by 3. The resulting type is
1047 * equivalent to the given type's cube-root.
1048 */
1049 template<class U> struct cbrt_base_impl;
1050 template<class... Exponents>
1051 struct cbrt_base_impl<base_unit<Exponents...>> {
1052 using type = base_unit<std::ratio_divide<Exponents, std::ratio<3>>...>;
1053 };
1054
1055 /**
1056 * @brief represents the cube-root type of a `base_unit` .
1057 * @details E.g. `cbrt<length_unit>` will represent `length_unit^(1/3)`.
1058 */
1059 template<class U> using cbrt_base = typename cbrt_base_impl<U>::type;
1060 }
1061 /** @endcond */ // END DOXYGEN IGNORE
1062
1063 //------------------------------
1064 // UNIT MANIPULATORS
1065 //------------------------------
1066
1067 /** @cond */ // DOXYGEN IGNORE
1068 namespace detail
1069 {
1070 /**
1071 * @brief implementation of `unit_multiply`.
1072 * @details multiplies two units. The base unit becomes the base units of each with their exponents
1073 * added together. The conversion factors of each are multiplied by each other. Pi exponent ratios
1074 * are added, and datum translations are removed.
1075 */
1076 template<class Unit1, class Unit2>
1077 struct unit_multiply_impl
1078 {
1079 using type = unit < std::ratio_multiply<typename Unit1::conversion_ratio, typename Unit2::conversion_ratio>,
1080 base_unit_multiply <traits::base_unit_of<typename Unit1::base_unit_type>, traits::base_unit_of<typename Unit2::base_unit_type>>,
1081 std::ratio_add<typename Unit1::pi_exponent_ratio, typename Unit2::pi_exponent_ratio>,
1082 std::ratio < 0 >> ;
1083 };
1084
1085 /**
1086 * @brief represents the type of two units multiplied together.
1087 * @details recalculates conversion and exponent ratios at compile-time.
1088 */
1089 template<class U1, class U2>
1090 using unit_multiply = typename unit_multiply_impl<U1, U2>::type;
1091
1092 /**
1093 * @brief implementation of `unit_divide`.
1094 * @details divides two units. The base unit becomes the base units of each with their exponents
1095 * subtracted from each other. The conversion factors of each are divided by each other. Pi exponent ratios
1096 * are subtracted, and datum translations are removed.
1097 */
1098 template<class Unit1, class Unit2>
1099 struct unit_divide_impl
1100 {
1101 using type = unit < std::ratio_divide<typename Unit1::conversion_ratio, typename Unit2::conversion_ratio>,
1102 base_unit_divide<traits::base_unit_of<typename Unit1::base_unit_type>, traits::base_unit_of<typename Unit2::base_unit_type>>,
1103 std::ratio_subtract<typename Unit1::pi_exponent_ratio, typename Unit2::pi_exponent_ratio>,
1104 std::ratio < 0 >> ;
1105 };
1106
1107 /**
1108 * @brief represents the type of two units divided by each other.
1109 * @details recalculates conversion and exponent ratios at compile-time.
1110 */
1111 template<class U1, class U2>
1112 using unit_divide = typename unit_divide_impl<U1, U2>::type;
1113
1114 /**
1115 * @brief implementation of `inverse`
1116 * @details inverts a unit (equivalent to 1/unit). The `base_unit` and pi exponents are all multiplied by
1117 * -1. The conversion ratio numerator and denominator are swapped. Datum translation
1118 * ratios are removed.
1119 */
1120 template<class Unit>
1121 struct inverse_impl
1122 {
1123 using type = unit < std::ratio<Unit::conversion_ratio::den, Unit::conversion_ratio::num>,
1124 inverse_base<traits::base_unit_of<typename units::traits::unit_traits<Unit>::base_unit_type>>,
1125 std::ratio_multiply<typename units::traits::unit_traits<Unit>::pi_exponent_ratio, std::ratio<-1>>,
1126 std::ratio < 0 >> ; // inverses are rates or change, the translation factor goes away.
1127 };
1128 }
1129 /** @endcond */ // END DOXYGEN IGNORE
1130
1131 /**
1132 * @brief represents the inverse unit type of `class U`.
1133 * @ingroup UnitManipulators
1134 * @tparam U `unit` type to invert.
1135 * @details E.g. `inverse<meters>` will represent meters^-1 (i.e. 1/meters).
1136 */
1137 template<class U> using inverse = typename units::detail::inverse_impl<U>::type;
1138
1139 /** @cond */ // DOXYGEN IGNORE
1140 namespace detail
1141 {
1142 /**
1143 * @brief implementation of `squared`
1144 * @details Squares the conversion ratio, `base_unit` exponents, pi exponents, and removes
1145 * datum translation ratios.
1146 */
1147 template<class Unit>
1148 struct squared_impl
1149 {
1150 static_assert(traits::is_unit<Unit>::value, "Template parameter `Unit` must be a `unit` type.");
1151 using Conversion = typename Unit::conversion_ratio;
1153 squared_base<traits::base_unit_of<typename Unit::base_unit_type>>,
1154 std::ratio_multiply<typename Unit::pi_exponent_ratio, std::ratio<2>>,
1155 typename Unit::translation_ratio
1156 > ;
1157 };
1158 }
1159 /** @endcond */ // END DOXYGEN IGNORE
1160
1161 /**
1162 * @brief represents the unit type of `class U` squared
1163 * @ingroup UnitManipulators
1164 * @tparam U `unit` type to square.
1165 * @details E.g. `square<meters>` will represent meters^2.
1166 */
1167 template<class U>
1169
1170 /** @cond */ // DOXYGEN IGNORE
1171 namespace detail
1172 {
1173 /**
1174 * @brief implementation of `cubed`
1175 * @details Cubes the conversion ratio, `base_unit` exponents, pi exponents, and removes
1176 * datum translation ratios.
1177 */
1178 template<class Unit>
1179 struct cubed_impl
1180 {
1181 static_assert(traits::is_unit<Unit>::value, "Template parameter `Unit` must be a `unit` type.");
1182 using Conversion = typename Unit::conversion_ratio;
1184 cubed_base<traits::base_unit_of<typename Unit::base_unit_type>>,
1185 std::ratio_multiply<typename Unit::pi_exponent_ratio, std::ratio<3>>,
1186 typename Unit::translation_ratio> ;
1187 };
1188 }
1189 /** @endcond */ // END DOXYGEN IGNORE
1190
1191 /**
1192 * @brief represents the type of `class U` cubed.
1193 * @ingroup UnitManipulators
1194 * @tparam U `unit` type to cube.
1195 * @details E.g. `cubed<meters>` will represent meters^3.
1196 */
1197 template<class U>
1199
1200 /** @cond */ // DOXYGEN IGNORE
1201 namespace detail
1202 {
1203 //----------------------------------
1204 // RATIO_SQRT IMPLEMENTATION
1205 //----------------------------------
1206
1207 using Zero = std::ratio<0>;
1208 using One = std::ratio<1>;
1209 template <typename R> using Square = std::ratio_multiply<R, R>;
1210
1211 // Find the largest std::integer N such that Predicate<N>::value is true.
1212 template <template <std::intmax_t N> class Predicate, typename enabled = void>
1213 struct BinarySearch {
1214 template <std::intmax_t N>
1215 struct SafeDouble_ {
1216 static constexpr const std::intmax_t value = 2 * N;
1217 static_assert(value > 0, "Overflows when computing 2 * N");
1218 };
1219
1220 template <intmax_t Lower, intmax_t Upper, typename Condition1 = void, typename Condition2 = void>
1221 struct DoubleSidedSearch_ : DoubleSidedSearch_<Lower, Upper,
1222 std::integral_constant<bool, (Upper - Lower == 1)>,
1223 std::integral_constant<bool, ((Upper - Lower>1 && Predicate<Lower + (Upper - Lower) / 2>::value))>> {};
1224
1225 template <intmax_t Lower, intmax_t Upper>
1226 struct DoubleSidedSearch_<Lower, Upper, std::false_type, std::false_type> : DoubleSidedSearch_<Lower, Lower + (Upper - Lower) / 2> {};
1227
1228 template <intmax_t Lower, intmax_t Upper, typename Condition2>
1229 struct DoubleSidedSearch_<Lower, Upper, std::true_type, Condition2> : std::integral_constant<intmax_t, Lower>{};
1230
1231 template <intmax_t Lower, intmax_t Upper, typename Condition1>
1232 struct DoubleSidedSearch_<Lower, Upper, Condition1, std::true_type> : DoubleSidedSearch_<Lower + (Upper - Lower) / 2, Upper>{};
1233
1234 template <std::intmax_t Lower, class enabled1 = void>
1235 struct SingleSidedSearch_ : SingleSidedSearch_<Lower, std::integral_constant<bool, Predicate<SafeDouble_<Lower>::value>::value>>{};
1236
1237 template <std::intmax_t Lower>
1238 struct SingleSidedSearch_<Lower, std::false_type> : DoubleSidedSearch_<Lower, SafeDouble_<Lower>::value> {};
1239
1240 template <std::intmax_t Lower>
1241 struct SingleSidedSearch_<Lower, std::true_type> : SingleSidedSearch_<SafeDouble_<Lower>::value>{};
1242
1243 static constexpr const std::intmax_t value = SingleSidedSearch_<1>::value;
1244 };
1245
1246 template <template <std::intmax_t N> class Predicate>
1247 struct BinarySearch<Predicate, std::enable_if_t<!Predicate<1>::value>> : std::integral_constant<std::intmax_t, 0>{};
1248
1249 // Find largest std::integer N such that N<=sqrt(R)
1250 template <typename R>
1251 struct Integer {
1252 template <std::intmax_t N> using Predicate_ = std::ratio_less_equal<std::ratio<N>, std::ratio_divide<R, std::ratio<N>>>;
1253 static constexpr const std::intmax_t value = BinarySearch<Predicate_>::value;
1254 };
1255
1256 template <typename R>
1257 struct IsPerfectSquare {
1258 static constexpr const std::intmax_t DenSqrt_ = Integer<std::ratio<R::den>>::value;
1259 static constexpr const std::intmax_t NumSqrt_ = Integer<std::ratio<R::num>>::value;
1260 static constexpr const bool value =( DenSqrt_ * DenSqrt_ == R::den && NumSqrt_ * NumSqrt_ == R::num);
1261 using Sqrt = std::ratio<NumSqrt_, DenSqrt_>;
1262 };
1263
1264 // Represents sqrt(P)-Q.
1265 template <typename Tp, typename Tq>
1266 struct Remainder {
1267 using P = Tp;
1268 using Q = Tq;
1269 };
1270
1271 // Represents 1/R = I + Rem where R is a Remainder.
1272 template <typename R>
1273 struct Reciprocal {
1274 using P_ = typename R::P;
1275 using Q_ = typename R::Q;
1276 using Den_ = std::ratio_subtract<P_, Square<Q_>>;
1277 using A_ = std::ratio_divide<Q_, Den_>;
1278 using B_ = std::ratio_divide<P_, Square<Den_>>;
1279 static constexpr const std::intmax_t I_ = (A_::num + Integer<std::ratio_multiply<B_, Square<std::ratio<A_::den>>>>::value) / A_::den;
1280 using I = std::ratio<I_>;
1281 using Rem = Remainder<B_, std::ratio_subtract<I, A_>>;
1282 };
1283
1284 // Expands sqrt(R) to continued fraction:
1285 // f(x)=C1+1/(C2+1/(C3+1/(...+1/(Cn+x)))) = (U*x+V)/(W*x+1) and sqrt(R)=f(Rem).
1286 // The error |f(Rem)-V| = |(U-W*V)x/(W*x+1)| <= |U-W*V|*Rem <= |U-W*V|/I' where
1287 // I' is the std::integer part of reciprocal of Rem.
1288 template <typename Tr, std::intmax_t N>
1289 struct ContinuedFraction {
1290 template <typename T>
1291 using Abs_ = std::conditional_t<std::ratio_less<T, Zero>::value, std::ratio_subtract<Zero, T>, T>;
1292
1293 using R = Tr;
1294 using Last_ = ContinuedFraction<R, N - 1>;
1295 using Reciprocal_ = Reciprocal<typename Last_::Rem>;
1296 using Rem = typename Reciprocal_::Rem;
1297 using I_ = typename Reciprocal_::I;
1298 using Den_ = std::ratio_add<typename Last_::W, I_>;
1299 using U = std::ratio_divide<typename Last_::V, Den_>;
1300 using V = std::ratio_divide<std::ratio_add<typename Last_::U, std::ratio_multiply<typename Last_::V, I_>>, Den_>;
1301 using W = std::ratio_divide<One, Den_>;
1302 using Error = Abs_<std::ratio_divide<std::ratio_subtract<U, std::ratio_multiply<V, W>>, typename Reciprocal<Rem>::I>>;
1303 };
1304
1305 template <typename Tr>
1306 struct ContinuedFraction<Tr, 1> {
1307 using R = Tr;
1308 using U = One;
1309 using V = std::ratio<Integer<R>::value>;
1310 using W = Zero;
1311 using Rem = Remainder<R, V>;
1312 using Error = std::ratio_divide<One, typename Reciprocal<Rem>::I>;
1313 };
1314
1315 template <typename R, typename Eps, std::intmax_t N = 1, typename enabled = void>
1316 struct Sqrt_ : Sqrt_<R, Eps, N + 1> {};
1317
1318 template <typename R, typename Eps, std::intmax_t N>
1319 struct Sqrt_<R, Eps, N, std::enable_if_t<std::ratio_less_equal<typename ContinuedFraction<R, N>::Error, Eps>::value>> {
1320 using type = typename ContinuedFraction<R, N>::V;
1321 };
1322
1323 template <typename R, typename Eps, typename enabled = void>
1324 struct Sqrt {
1325 static_assert(std::ratio_greater_equal<R, Zero>::value, "R can't be negative");
1326 };
1327
1328 template <typename R, typename Eps>
1329 struct Sqrt<R, Eps, std::enable_if_t<std::ratio_greater_equal<R, Zero>::value && IsPerfectSquare<R>::value>> {
1330 using type = typename IsPerfectSquare<R>::Sqrt;
1331 };
1332
1333 template <typename R, typename Eps>
1334 struct Sqrt<R, Eps, std::enable_if_t<(std::ratio_greater_equal<R, Zero>::value && !IsPerfectSquare<R>::value)>> : Sqrt_<R, Eps>{};
1335 }
1336 /** @endcond */ // END DOXYGEN IGNORE
1337
1338 /**
1339 * @ingroup TypeTraits
1340 * @brief Calculate square root of a ratio at compile-time
1341 * @details Calculates a rational approximation of the square root of the ratio. The error
1342 * in the calculation is bounded by 1/epsilon (Eps). E.g. for the default value
1343 * of 10000000000, the maximum error will be a/10000000000, or 1e-8, or said another way,
1344 * the error will be on the order of 10^-9. Since these calculations are done at
1345 * compile time, it is advisable to set epsilon to the highest value that does not
1346 * cause an integer overflow in the calculation. If you can't compile `ratio_sqrt`
1347 * due to overflow errors, reducing the value of epsilon sufficiently will correct
1348 * the problem.\n\n
1349 * `ratio_sqrt` is guaranteed to converge for all values of `Ratio` which do not
1350 * overflow.
1351 * @note This function provides a rational approximation, _NOT_ an exact value.
1352 * @tparam Ratio ratio to take the square root of. This can represent any rational value,
1353 * _not_ just integers or values with integer roots.
1354 * @tparam Eps Value of epsilon, which represents the inverse of the maximum allowable
1355 * error. This value should be chosen to be as high as possible before
1356 * integer overflow errors occur in the compiler.
1357 */
1358 template<typename Ratio, std::intmax_t Eps = 10000000000>
1359 using ratio_sqrt = typename units::detail::Sqrt<Ratio, std::ratio<1, Eps>>::type;
1360
1361 /** @cond */ // DOXYGEN IGNORE
1362 namespace detail
1363 {
1364 /**
1365 * @brief implementation of `sqrt`
1366 * @details square roots the conversion ratio, `base_unit` exponents, pi exponents, and removes
1367 * datum translation ratios.
1368 */
1369 template<class Unit, std::intmax_t Eps>
1370 struct sqrt_impl
1371 {
1372 static_assert(traits::is_unit<Unit>::value, "Template parameter `Unit` must be a `unit` type.");
1373 using Conversion = typename Unit::conversion_ratio;
1375 sqrt_base<traits::base_unit_of<typename Unit::base_unit_type>>,
1376 std::ratio_divide<typename Unit::pi_exponent_ratio, std::ratio<2>>,
1377 typename Unit::translation_ratio>;
1378 };
1379 }
1380 /** @endcond */ // END DOXYGEN IGNORE
1381
1382 /**
1383 * @ingroup UnitManipulators
1384 * @brief represents the square root of type `class U`.
1385 * @details Calculates a rational approximation of the square root of the unit. The error
1386 * in the calculation is bounded by 1/epsilon (Eps). E.g. for the default value
1387 * of 10000000000, the maximum error will be a/10000000000, or 1e-8, or said another way,
1388 * the error will be on the order of 10^-9. Since these calculations are done at
1389 * compile time, it is advisable to set epsilon to the highest value that does not
1390 * cause an integer overflow in the calculation. If you can't compile `ratio_sqrt`
1391 * due to overflow errors, reducing the value of epsilon sufficiently will correct
1392 * the problem.\n\n
1393 * `ratio_sqrt` is guaranteed to converge for all values of `Ratio` which do not
1394 * overflow.
1395 * @tparam U `unit` type to take the square root of.
1396 * @tparam Eps Value of epsilon, which represents the inverse of the maximum allowable
1397 * error. This value should be chosen to be as high as possible before
1398 * integer overflow errors occur in the compiler.
1399 * @note USE WITH CAUTION. The is an approximate value. In general, squared<sqrt<meter>> != meter,
1400 * i.e. the operation is not reversible, and it will result in propagated approximations.
1401 * Use only when absolutely necessary.
1402 */
1403 template<class U, std::intmax_t Eps = 10000000000>
1405
1406 //------------------------------
1407 // COMPOUND UNITS
1408 //------------------------------
1409
1410 /** @cond */ // DOXYGEN IGNORE
1411 namespace detail
1412 {
1413 /**
1414 * @brief implementation of compound_unit
1415 * @details multiplies a variadic list of units together, and is inherited from the resulting
1416 * type.
1417 */
1418 template<class U, class... Us> struct compound_impl;
1419 template<class U> struct compound_impl<U> { using type = U; };
1420 template<class U1, class U2, class...Us>
1421 struct compound_impl<U1, U2, Us...>
1422 : compound_impl<unit_multiply<U1, U2>, Us...> {};
1423 }
1424 /** @endcond */ // END DOXYGEN IGNORE
1425
1426 /**
1427 * @brief Represents a unit type made up from other units.
1428 * @details Compound units are formed by multiplying the units of all the types provided in
1429 * the template argument. Types provided must inherit from `unit`. A compound unit can
1430 * be formed from any number of other units, and unit manipulators like `inverse` and
1431 * `squared` are supported. E.g. to specify acceleration, on could create
1432 * `using acceleration = compound_unit<length::meters, inverse<squared<seconds>>;`
1433 * @tparam U... units which, when multiplied together, form the desired compound unit.
1434 * @ingroup UnitTypes
1435 */
1436 template<class U, class... Us>
1437 using compound_unit = typename units::detail::compound_impl<U, Us...>::type;
1438
1439 //------------------------------
1440 // PREFIXES
1441 //------------------------------
1442
1443 /** @cond */ // DOXYGEN IGNORE
1444 namespace detail
1445 {
1446 /**
1447 * @brief prefix applicator.
1448 * @details creates a unit type from a prefix and a unit
1449 */
1450 template<class Ratio, class Unit>
1451 struct prefix
1452 {
1453 static_assert(traits::is_ratio<Ratio>::value, "Template parameter `Ratio` must be a `std::ratio`.");
1454 static_assert(traits::is_unit<Unit>::value, "Template parameter `Unit` must be a `unit` type.");
1455 typedef typename units::unit<Ratio, Unit> type;
1456 };
1457
1458 /// recursive exponential implementation
1459 template <int N, class U>
1460 struct power_of_ratio
1461 {
1462 typedef std::ratio_multiply<U, typename power_of_ratio<N - 1, U>::type> type;
1463 };
1464
1465 /// End recursion
1466 template <class U>
1467 struct power_of_ratio<1, U>
1468 {
1469 typedef U type;
1470 };
1471 }
1472 /** @endcond */ // END DOXYGEN IGNORE
1473
1474 /**
1475 * @ingroup UnitManipulators
1476 * @{
1477 * @ingroup Decimal Prefixes
1478 * @{
1479 */
1480 template<class U> using atto = typename units::detail::prefix<std::atto, U>::type; ///< Represents the type of `class U` with the metric 'atto' prefix appended. @details E.g. atto<meters> represents meters*10^-18 @tparam U unit type to apply the prefix to.
1481 template<class U> using femto = typename units::detail::prefix<std::femto,U>::type; ///< Represents the type of `class U` with the metric 'femto' prefix appended. @details E.g. femto<meters> represents meters*10^-15 @tparam U unit type to apply the prefix to.
1482 template<class U> using pico = typename units::detail::prefix<std::pico, U>::type; ///< Represents the type of `class U` with the metric 'pico' prefix appended. @details E.g. pico<meters> represents meters*10^-12 @tparam U unit type to apply the prefix to.
1483 template<class U> using nano = typename units::detail::prefix<std::nano, U>::type; ///< Represents the type of `class U` with the metric 'nano' prefix appended. @details E.g. nano<meters> represents meters*10^-9 @tparam U unit type to apply the prefix to.
1484 template<class U> using micro = typename units::detail::prefix<std::micro,U>::type; ///< Represents the type of `class U` with the metric 'micro' prefix appended. @details E.g. micro<meters> represents meters*10^-6 @tparam U unit type to apply the prefix to.
1485 template<class U> using milli = typename units::detail::prefix<std::milli,U>::type; ///< Represents the type of `class U` with the metric 'milli' prefix appended. @details E.g. milli<meters> represents meters*10^-3 @tparam U unit type to apply the prefix to.
1486 template<class U> using centi = typename units::detail::prefix<std::centi,U>::type; ///< Represents the type of `class U` with the metric 'centi' prefix appended. @details E.g. centi<meters> represents meters*10^-2 @tparam U unit type to apply the prefix to.
1487 template<class U> using deci = typename units::detail::prefix<std::deci, U>::type; ///< Represents the type of `class U` with the metric 'deci' prefix appended. @details E.g. deci<meters> represents meters*10^-1 @tparam U unit type to apply the prefix to.
1488 template<class U> using deca = typename units::detail::prefix<std::deca, U>::type; ///< Represents the type of `class U` with the metric 'deca' prefix appended. @details E.g. deca<meters> represents meters*10^1 @tparam U unit type to apply the prefix to.
1489 template<class U> using hecto = typename units::detail::prefix<std::hecto,U>::type; ///< Represents the type of `class U` with the metric 'hecto' prefix appended. @details E.g. hecto<meters> represents meters*10^2 @tparam U unit type to apply the prefix to.
1490 template<class U> using kilo = typename units::detail::prefix<std::kilo, U>::type; ///< Represents the type of `class U` with the metric 'kilo' prefix appended. @details E.g. kilo<meters> represents meters*10^3 @tparam U unit type to apply the prefix to.
1491 template<class U> using mega = typename units::detail::prefix<std::mega, U>::type; ///< Represents the type of `class U` with the metric 'mega' prefix appended. @details E.g. mega<meters> represents meters*10^6 @tparam U unit type to apply the prefix to.
1492 template<class U> using giga = typename units::detail::prefix<std::giga, U>::type; ///< Represents the type of `class U` with the metric 'giga' prefix appended. @details E.g. giga<meters> represents meters*10^9 @tparam U unit type to apply the prefix to.
1493 template<class U> using tera = typename units::detail::prefix<std::tera, U>::type; ///< Represents the type of `class U` with the metric 'tera' prefix appended. @details E.g. tera<meters> represents meters*10^12 @tparam U unit type to apply the prefix to.
1494 template<class U> using peta = typename units::detail::prefix<std::peta, U>::type; ///< Represents the type of `class U` with the metric 'peta' prefix appended. @details E.g. peta<meters> represents meters*10^15 @tparam U unit type to apply the prefix to.
1495 template<class U> using exa = typename units::detail::prefix<std::exa, U>::type; ///< Represents the type of `class U` with the metric 'exa' prefix appended. @details E.g. exa<meters> represents meters*10^18 @tparam U unit type to apply the prefix to.
1496 /** @} @} */
1497
1498 /**
1499 * @ingroup UnitManipulators
1500 * @{
1501 * @ingroup Binary Prefixes
1502 * @{
1503 */
1504 template<class U> using kibi = typename units::detail::prefix<std::ratio<1024>, U>::type; ///< Represents the type of `class U` with the binary 'kibi' prefix appended. @details E.g. kibi<bytes> represents bytes*2^10 @tparam U unit type to apply the prefix to.
1505 template<class U> using mebi = typename units::detail::prefix<std::ratio<1048576>, U>::type; ///< Represents the type of `class U` with the binary 'mibi' prefix appended. @details E.g. mebi<bytes> represents bytes*2^20 @tparam U unit type to apply the prefix to.
1506 template<class U> using gibi = typename units::detail::prefix<std::ratio<1073741824>, U>::type; ///< Represents the type of `class U` with the binary 'gibi' prefix appended. @details E.g. gibi<bytes> represents bytes*2^30 @tparam U unit type to apply the prefix to.
1507 template<class U> using tebi = typename units::detail::prefix<std::ratio<1099511627776>, U>::type; ///< Represents the type of `class U` with the binary 'tebi' prefix appended. @details E.g. tebi<bytes> represents bytes*2^40 @tparam U unit type to apply the prefix to.
1508 template<class U> using pebi = typename units::detail::prefix<std::ratio<1125899906842624>, U>::type; ///< Represents the type of `class U` with the binary 'pebi' prefix appended. @details E.g. pebi<bytes> represents bytes*2^50 @tparam U unit type to apply the prefix to.
1509 template<class U> using exbi = typename units::detail::prefix<std::ratio<1152921504606846976>, U>::type; ///< Represents the type of `class U` with the binary 'exbi' prefix appended. @details E.g. exbi<bytes> represents bytes*2^60 @tparam U unit type to apply the prefix to.
1510 /** @} @} */
1511
1512 //------------------------------
1513 // CONVERSION TRAITS
1514 //------------------------------
1515
1516 namespace traits
1517 {
1518 /**
1519 * @ingroup TypeTraits
1520 * @brief Trait which checks whether two units can be converted to each other
1521 * @details Inherits from `std::true_type` or `std::false_type`. Use `is_convertible_unit<U1, U2>::value` to test
1522 * whether `class U1` is convertible to `class U2`. Note: convertible has both the semantic meaning,
1523 * (i.e. meters can be converted to feet), and the c++ meaning of conversion (type meters can be
1524 * converted to type feet). Conversion is always symmetric, so if U1 is convertible to U2, then
1525 * U2 will be convertible to U1.
1526 * @tparam U1 Unit to convert from.
1527 * @tparam U2 Unit to convert to.
1528 * @sa is_convertible_unit_t
1529 */
1530 template<class U1, class U2>
1531 struct is_convertible_unit : std::is_same <traits::base_unit_of<typename units::traits::unit_traits<U1>::base_unit_type>,
1532 base_unit_of<typename units::traits::unit_traits<U2>::base_unit_type >> {};
1533 template<class U1, class U2>
1535 }
1536
1537 //------------------------------
1538 // CONVERSION FUNCTION
1539 //------------------------------
1540
1541 /** @cond */ // DOXYGEN IGNORE
1542 namespace detail
1543 {
1544 constexpr inline UNIT_LIB_DEFAULT_TYPE pow(UNIT_LIB_DEFAULT_TYPE x, unsigned long long y)
1545 {
1546 return y == 0 ? 1.0 : x * pow(x, y - 1);
1547 }
1548
1550 {
1551 return x < 0 ? -x : x;
1552 }
1553
1554 /// convert dispatch for units which are both the same
1555 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1556 static inline constexpr T convert(const T& value, std::true_type, std::false_type, std::false_type) noexcept
1557 {
1558 return value;
1559 }
1560
1561 /// convert dispatch for units which are both the same
1562 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1563 static inline constexpr T convert(const T& value, std::true_type, std::false_type, std::true_type) noexcept
1564 {
1565 return value;
1566 }
1567
1568 /// convert dispatch for units which are both the same
1569 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1570 static inline constexpr T convert(const T& value, std::true_type, std::true_type, std::false_type) noexcept
1571 {
1572 return value;
1573 }
1574
1575 /// convert dispatch for units which are both the same
1576 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1577 static inline constexpr T convert(const T& value, std::true_type, std::true_type, std::true_type) noexcept
1578 {
1579 return value;
1580 }
1581
1582 /// convert dispatch for units of different types w/ no translation and no PI
1583 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1584 static inline constexpr T convert(const T& value, std::false_type, std::false_type, std::false_type) noexcept
1585 {
1586 return ((value * Ratio::num) / Ratio::den);
1587 }
1588
1589 /// convert dispatch for units of different types w/ no translation, but has PI in numerator
1590 // constepxr with PI in numerator
1591 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1592 static inline constexpr
1593 std::enable_if_t<(PiRatio::num / PiRatio::den >= 1 && PiRatio::num % PiRatio::den == 0), T>
1594 convert(const T& value, std::false_type, std::true_type, std::false_type) noexcept
1595 {
1596 return ((value * pow(constants::detail::PI_VAL, PiRatio::num / PiRatio::den) * Ratio::num) / Ratio::den);
1597 }
1598
1599 /// convert dispatch for units of different types w/ no translation, but has PI in denominator
1600 // constexpr with PI in denominator
1601 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1602 static inline constexpr
1603 std::enable_if_t<(PiRatio::num / PiRatio::den <= -1 && PiRatio::num % PiRatio::den == 0), T>
1604 convert(const T& value, std::false_type, std::true_type, std::false_type) noexcept
1605 {
1606 return (value * Ratio::num) / (Ratio::den * pow(constants::detail::PI_VAL, -PiRatio::num / PiRatio::den));
1607 }
1608
1609 /// convert dispatch for units of different types w/ no translation, but has PI in numerator
1610 // Not constexpr - uses std::pow
1611 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1612 static inline // sorry, this can't be constexpr!
1613 std::enable_if_t<(PiRatio::num / PiRatio::den < 1 && PiRatio::num / PiRatio::den > -1), T>
1614 convert(const T& value, std::false_type, std::true_type, std::false_type) noexcept
1615 {
1616 return ((value * std::pow(constants::detail::PI_VAL, PiRatio::num / PiRatio::den) * Ratio::num) / Ratio::den);
1617 }
1618
1619 /// convert dispatch for units of different types with a translation, but no PI
1620 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1621 static inline constexpr T convert(const T& value, std::false_type, std::false_type, std::true_type) noexcept
1622 {
1623 return ((value * Ratio::num) / Ratio::den) + (static_cast<UNIT_LIB_DEFAULT_TYPE>(Translation::num) / Translation::den);
1624 }
1625
1626 /// convert dispatch for units of different types with a translation AND PI
1627 template<class UnitFrom, class UnitTo, class Ratio, class PiRatio, class Translation, typename T>
1628 static inline constexpr T convert(const T& value, const std::false_type, const std::true_type, const std::true_type) noexcept
1629 {
1630 return ((value * std::pow(constants::detail::PI_VAL, PiRatio::num / PiRatio::den) * Ratio::num) / Ratio::den) + (static_cast<UNIT_LIB_DEFAULT_TYPE>(Translation::num) / Translation::den);
1631 }
1632 }
1633 /** @endcond */ // END DOXYGEN IGNORE
1634
1635 /**
1636 * @ingroup Conversion
1637 * @brief converts a <i>value</i> from one type to another.
1638 * @details Converts a <i>value</i> of a built-in arithmetic type to another unit. This does not change
1639 * the type of <i>value</i>, only what it contains. E.g. @code double result = convert<length::meters, length::feet>(1.0); // result == 3.28084 @endcode
1640 * @sa unit_t for implicit conversion of unit containers.
1641 * @tparam UnitFrom unit tag to convert <i>value</i> from. Must be a `unit` type (i.e. is_unit<UnitFrom>::value == true),
1642 * and must be convertible to `UnitTo` (i.e. is_convertible_unit<UnitFrom, UnitTo>::value == true).
1643 * @tparam UnitTo unit tag to convert <i>value</i> to. Must be a `unit` type (i.e. is_unit<UnitTo>::value == true),
1644 * and must be convertible from `UnitFrom` (i.e. is_convertible_unit<UnitFrom, UnitTo>::value == true).
1645 * @tparam T type of <i>value</i>. It is inferred from <i>value</i>, and is expected to be a built-in arithmetic type.
1646 * @param[in] value Arithmetic value to convert from `UnitFrom` to `UnitTo`. The value should represent
1647 * a quantity in units of `UnitFrom`.
1648 * @returns value, converted from units of `UnitFrom` to `UnitTo`.
1649 */
1650 template<class UnitFrom, class UnitTo, typename T = UNIT_LIB_DEFAULT_TYPE>
1651 static inline constexpr T convert(const T& value) noexcept
1652 {
1653 static_assert(traits::is_unit<UnitFrom>::value, "Template parameter `UnitFrom` must be a `unit` type.");
1654 static_assert(traits::is_unit<UnitTo>::value, "Template parameter `UnitTo` must be a `unit` type.");
1655 static_assert(traits::is_convertible_unit<UnitFrom, UnitTo>::value, "Units are not compatible.");
1656
1657 using Ratio = std::ratio_divide<typename UnitFrom::conversion_ratio, typename UnitTo::conversion_ratio>;
1658 using PiRatio = std::ratio_subtract<typename UnitFrom::pi_exponent_ratio, typename UnitTo::pi_exponent_ratio>;
1659 using Translation = std::ratio_divide<std::ratio_subtract<typename UnitFrom::translation_ratio, typename UnitTo::translation_ratio>, typename UnitTo::conversion_ratio>;
1660
1661 using isSame = typename std::is_same<std::decay_t<UnitFrom>, std::decay_t<UnitTo>>::type;
1662 using piRequired = std::integral_constant<bool, !(std::is_same<std::ratio<0>, PiRatio>::value)>;
1663 using translationRequired = std::integral_constant<bool, !(std::is_same<std::ratio<0>, Translation>::value)>;
1664
1665 return units::detail::convert<UnitFrom, UnitTo, Ratio, PiRatio, Translation, T>
1666 (value, isSame{}, piRequired{}, translationRequired{});
1667 }
1668
1669 //----------------------------------
1670 // NON-LINEAR SCALE TRAITS
1671 //----------------------------------
1672
1673 /** @cond */ // DOXYGEN IGNORE
1674 namespace traits
1675 {
1676 namespace detail
1677 {
1678 /**
1679 * @brief implementation of has_operator_parenthesis
1680 * @details checks that operator() returns the same type as `Ret`
1681 */
1682 template<class T, class Ret>
1683 struct has_operator_parenthesis_impl
1684 {
1685 template<class U>
1686 static constexpr auto test(U*) -> decltype(std::declval<U>()()) { return decltype(std::declval<U>()()){}; }
1687 template<typename>
1688 static constexpr std::false_type test(...) { return std::false_type{}; }
1689
1690 using type = typename std::is_same<Ret, decltype(test<T>(0))>::type;
1691 };
1692 }
1693
1694 /**
1695 * @brief checks that `class T` has an `operator()` member which returns `Ret`
1696 * @details used as part of the linear_scale concept.
1697 */
1698 template<class T, class Ret>
1699 struct has_operator_parenthesis : traits::detail::has_operator_parenthesis_impl<T, Ret>::type {};
1700 }
1701
1702 namespace traits
1703 {
1704 namespace detail
1705 {
1706 /**
1707 * @brief implementation of has_value_member
1708 * @details checks for a member named `m_member` with type `Ret`
1709 */
1710 template<class T, class Ret>
1711 struct has_value_member_impl
1712 {
1713 template<class U>
1714 static constexpr auto test(U* p) -> decltype(p->m_value) { return p->m_value; }
1715 template<typename>
1716 static constexpr auto test(...)->std::false_type { return std::false_type{}; }
1717
1718 using type = typename std::is_same<std::decay_t<Ret>, std::decay_t<decltype(test<T>(0))>>::type;
1719 };
1720 }
1721
1722 /**
1723 * @brief checks for a member named `m_member` with type `Ret`
1724 * @details used as part of the linear_scale concept checker.
1725 */
1726 template<class T, class Ret>
1727 struct has_value_member : traits::detail::has_value_member_impl<T, Ret>::type {};
1728 template<class T, class Ret>
1729 inline constexpr bool has_value_member_v = has_value_member<T, Ret>::value;
1730 }
1731 /** @endcond */ // END DOXYGEN IGNORE
1732
1733 namespace traits
1734 {
1735 /**
1736 * @ingroup TypeTraits
1737 * @brief Trait which tests that `class T` meets the requirements for a non-linear scale
1738 * @details A non-linear scale must:
1739 * - be default constructible
1740 * - have an `operator()` member which returns the non-linear value stored in the scale
1741 * - have an accessible `m_value` member type which stores the linearized value in the scale.
1742 *
1743 * Linear/nonlinear scales are used by `units::unit` to store values and scale them
1744 * if they represent things like dB.
1745 */
1746 template<class T, class Ret>
1747 struct is_nonlinear_scale : std::integral_constant<bool,
1748 std::is_default_constructible<T>::value &&
1749 has_operator_parenthesis<T, Ret>::value &&
1750 has_value_member<T, Ret>::value &&
1751 std::is_trivial<T>::value>
1752 {};
1753 }
1754
1755 //------------------------------
1756 // UNIT_T TYPE TRAITS
1757 //------------------------------
1758
1759 namespace traits
1760 {
1761#ifdef FOR_DOXYGEN_PURPOSOES_ONLY
1762 /**
1763 * @ingroup TypeTraits
1764 * @brief Trait for accessing the publicly defined types of `units::unit_t`
1765 * @details The units library determines certain properties of the unit_t types passed to them
1766 * and what they represent by using the members of the corresponding unit_t_traits instantiation.
1767 */
1768 template<typename T>
1769 struct unit_t_traits
1770 {
1771 typedef typename T::non_linear_scale_type non_linear_scale_type; ///< Type of the unit_t non_linear_scale (e.g. linear_scale, decibel_scale). This property is used to enable the proper linear or logarithmic arithmetic functions.
1772 typedef typename T::underlying_type underlying_type; ///< Underlying storage type of the `unit_t`, e.g. `double`.
1773 typedef typename T::value_type value_type; ///< Synonym for underlying type. May be removed in future versions. Prefer underlying_type.
1774 typedef typename T::unit_type unit_type; ///< Type of unit the `unit_t` represents, e.g. `meters`
1775 };
1776#endif
1777
1778 /** @cond */ // DOXYGEN IGNORE
1779 /**
1780 * @brief unit_t_traits specialization for things which are not unit_t
1781 * @details
1782 */
1783 template<typename T, typename = void>
1784 struct unit_t_traits
1785 {
1786 typedef void non_linear_scale_type;
1787 typedef void underlying_type;
1788 typedef void value_type;
1789 typedef void unit_type;
1790 };
1791
1792 /**
1793 * @ingroup TypeTraits
1794 * @brief Trait for accessing the publicly defined types of `units::unit_t`
1795 * @details
1796 */
1797 template<typename T>
1798 struct unit_t_traits <T, typename void_t<
1799 typename T::non_linear_scale_type,
1800 typename T::underlying_type,
1801 typename T::value_type,
1802 typename T::unit_type>::type>
1803 {
1804 typedef typename T::non_linear_scale_type non_linear_scale_type;
1805 typedef typename T::underlying_type underlying_type;
1806 typedef typename T::value_type value_type;
1807 typedef typename T::unit_type unit_type;
1808 };
1809 /** @endcond */ // END DOXYGEN IGNORE
1810 }
1811
1812 namespace traits
1813 {
1814 /**
1815 * @ingroup TypeTraits
1816 * @brief Trait which tests whether two container types derived from `unit_t` are convertible to each other
1817 * @details Inherits from `std::true_type` or `std::false_type`. Use `is_convertible_unit_t<U1, U2>::value` to test
1818 * whether `class U1` is convertible to `class U2`. Note: convertible has both the semantic meaning,
1819 * (i.e. meters can be converted to feet), and the c++ meaning of conversion (type meters can be
1820 * converted to type feet). Conversion is always symmetric, so if U1 is convertible to U2, then
1821 * U2 will be convertible to U1.
1822 * @tparam U1 Unit to convert from.
1823 * @tparam U2 Unit to convert to.
1824 * @sa is_convertible_unit
1825 */
1826 template<class U1, class U2>
1827 struct is_convertible_unit_t : std::integral_constant<bool,
1828 is_convertible_unit<typename units::traits::unit_t_traits<U1>::unit_type, typename units::traits::unit_t_traits<U2>::unit_type>::value>
1829 {};
1830 }
1831
1832 //----------------------------------
1833 // UNIT TYPE
1834 //----------------------------------
1835
1836 /** @cond */ // DOXYGEN IGNORE
1837 // forward declaration
1838 template<typename T> struct linear_scale;
1839 template<typename T> struct decibel_scale;
1840
1841 namespace detail
1842 {
1843 /**
1844 * @brief helper type to identify units.
1845 * @details A non-templated base class for `unit` which enables RTTI testing.
1846 */
1847 struct _unit_t {};
1848 }
1849 /** @endcond */ // END DOXYGEN IGNORE
1850
1851 namespace traits
1852 {
1853 // forward declaration
1854 #if !defined(_MSC_VER) || _MSC_VER > 1800 // bug in VS2013 prevents this from working
1855 template<typename... T> struct is_dimensionless_unit;
1856 #else
1857 template<typename T1, typename T2 = T1, typename T3 = T1> struct is_dimensionless_unit;
1858 #endif
1859
1860 /**
1861 * @ingroup TypeTraits
1862 * @brief Traits which tests if a class is a `unit`
1863 * @details Inherits from `std::true_type` or `std::false_type`. Use `is_unit<T>::value` to test
1864 * whether `class T` implements a `unit`.
1865 */
1866 template<class T>
1867 struct is_unit_t : std::is_base_of<units::detail::_unit_t, T>::type {};
1868 template<class T>
1869 inline constexpr bool is_unit_t_v = is_unit_t<T>::value;
1870 }
1871
1872 /**
1873 * @ingroup UnitContainers
1874 * @brief Container for values which represent quantities of a given unit.
1875 * @details Stores a value which represents a quantity in the given units. Unit containers
1876 * (except scalar values) are *not* convertible to built-in c++ types, in order to
1877 * provide type safety in dimensional analysis. Unit containers *are* implicitly
1878 * convertible to other compatible unit container types. Unit containers support
1879 * various types of arithmetic operations, depending on their scale type.
1880 *
1881 * The value of a `unit_t` can only be changed on construction, or by assignment
1882 * from another `unit_t` type. If necessary, the underlying value can be accessed
1883 * using `operator()`: @code
1884 * meter_t m(5.0);
1885 * double val = m(); // val == 5.0 @endcode.
1886 * @tparam Units unit tag for which type of units the `unit_t` represents (e.g. meters)
1887 * @tparam T underlying type of the storage. Defaults to double.
1888 * @tparam NonLinearScale optional scale class for the units. Defaults to linear (i.e. does
1889 * not scale the unit value). Examples of non-linear scales could be logarithmic,
1890 * decibel, or richter scales. Non-linear scales must adhere to the non-linear-scale
1891 * concept, i.e. `is_nonlinear_scale<...>::value` must be `true`.
1892 * @sa
1893 * - \ref lengthContainers "length unit containers"
1894 * - \ref massContainers "mass unit containers"
1895 * - \ref timeContainers "time unit containers"
1896 * - \ref angleContainers "angle unit containers"
1897 * - \ref currentContainers "current unit containers"
1898 * - \ref temperatureContainers "temperature unit containers"
1899 * - \ref substanceContainers "substance unit containers"
1900 * - \ref luminousIntensityContainers "luminous intensity unit containers"
1901 * - \ref solidAngleContainers "solid angle unit containers"
1902 * - \ref frequencyContainers "frequency unit containers"
1903 * - \ref velocityContainers "velocity unit containers"
1904 * - \ref angularVelocityContainers "angular velocity unit containers"
1905 * - \ref accelerationContainers "acceleration unit containers"
1906 * - \ref forceContainers "force unit containers"
1907 * - \ref pressureContainers "pressure unit containers"
1908 * - \ref chargeContainers "charge unit containers"
1909 * - \ref energyContainers "energy unit containers"
1910 * - \ref powerContainers "power unit containers"
1911 * - \ref voltageContainers "voltage unit containers"
1912 * - \ref capacitanceContainers "capacitance unit containers"
1913 * - \ref impedanceContainers "impedance unit containers"
1914 * - \ref magneticFluxContainers "magnetic flux unit containers"
1915 * - \ref magneticFieldStrengthContainers "magnetic field strength unit containers"
1916 * - \ref inductanceContainers "inductance unit containers"
1917 * - \ref luminousFluxContainers "luminous flux unit containers"
1918 * - \ref illuminanceContainers "illuminance unit containers"
1919 * - \ref radiationContainers "radiation unit containers"
1920 * - \ref torqueContainers "torque unit containers"
1921 * - \ref areaContainers "area unit containers"
1922 * - \ref volumeContainers "volume unit containers"
1923 * - \ref densityContainers "density unit containers"
1924 * - \ref concentrationContainers "concentration unit containers"
1925 * - \ref constantContainers "constant unit containers"
1926 */
1927 template<class Units, typename T = UNIT_LIB_DEFAULT_TYPE, template<typename> class NonLinearScale = linear_scale>
1928 class unit_t : public NonLinearScale<T>, units::detail::_unit_t
1929 {
1930 static_assert(traits::is_unit<Units>::value, "Template parameter `Units` must be a unit tag. Check that you aren't using a unit type (_t).");
1931 static_assert(traits::is_nonlinear_scale<NonLinearScale<T>, T>::value, "Template parameter `NonLinearScale` does not conform to the `is_nonlinear_scale` concept.");
1932
1933 protected:
1934
1935 using nls = NonLinearScale<T>;
1936 using nls::m_value;
1937
1938 public:
1939
1940 typedef NonLinearScale<T> non_linear_scale_type; ///< Type of the non-linear scale of the unit_t (e.g. linear_scale)
1941 typedef T underlying_type; ///< Type of the underlying storage of the unit_t (e.g. double)
1942 typedef T value_type; ///< Synonym for underlying type. May be removed in future versions. Prefer underlying_type.
1943 typedef Units unit_type; ///< Type of `unit` the `unit_t` represents (e.g. meters)
1944
1945 /**
1946 * @ingroup Constructors
1947 * @brief default constructor.
1948 */
1949 constexpr unit_t() = default;
1950
1951 /**
1952 * @brief constructor
1953 * @details constructs a new unit_t using the non-linear scale's constructor.
1954 * @param[in] value unit value magnitude.
1955 * @param[in] args additional constructor arguments are forwarded to the non-linear scale constructor. Which
1956 * args are required depends on which scale is used. For the default (linear) scale,
1957 * no additional args are necessary.
1958 */
1959 template<class... Args>
1960 inline explicit constexpr unit_t(const T value, const Args&... args) noexcept : nls(value, args...)
1961 {
1962
1963 }
1964
1965 /**
1966 * @brief constructor
1967 * @details enable implicit conversions from T types ONLY for linear scalar units
1968 * @param[in] value value of the unit_t
1969 */
1970 template<class Ty, class = typename std::enable_if<traits::is_dimensionless_unit<Units>::value && std::is_arithmetic<Ty>::value>::type>
1971 inline constexpr unit_t(const Ty value) noexcept : nls(value)
1972 {
1973
1974 }
1975
1976 /**
1977 * @brief chrono constructor
1978 * @details enable implicit conversions from std::chrono::duration types ONLY for time units
1979 * @param[in] value value of the unit_t
1980 */
1981 template<class Rep, class Period, class = std::enable_if_t<std::is_arithmetic<Rep>::value && traits::is_ratio<Period>::value>>
1982 inline constexpr unit_t(const std::chrono::duration<Rep, Period>& value) noexcept :
1983 nls(units::convert<unit<std::ratio<1,1000000000>, category::time_unit>, Units>(static_cast<T>(std::chrono::duration_cast<std::chrono::nanoseconds>(value).count())))
1984 {
1985
1986 }
1987
1988 /**
1989 * @brief copy constructor (converting)
1990 * @details performs implicit unit conversions if required.
1991 * @param[in] rhs unit to copy.
1992 */
1993 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs>
1994 inline constexpr unit_t(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) noexcept :
1995 nls(units::convert<UnitsRhs, Units, T>(rhs.m_value), std::true_type() /*store linear value*/)
1996 {
1997
1998 }
1999
2000 /**
2001 * @brief assignment
2002 * @details performs implicit unit conversions if required
2003 * @param[in] rhs unit to copy.
2004 */
2005 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs>
2006 inline unit_t& operator=(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) noexcept
2007 {
2008 nls::m_value = units::convert<UnitsRhs, Units, T>(rhs.m_value);
2009 return *this;
2010 }
2011
2012 /**
2013 * @brief assignment
2014 * @details performs implicit conversions from built-in types ONLY for scalar units
2015 * @param[in] rhs value to copy.
2016 */
2017 template<class Ty, class = std::enable_if_t<traits::is_dimensionless_unit<Units>::value && std::is_arithmetic<Ty>::value>>
2018 inline unit_t& operator=(const Ty& rhs) noexcept
2019 {
2020 nls::m_value = rhs;
2021 return *this;
2022 }
2023
2024 /**
2025 * @brief less-than
2026 * @details compares the linearized value of two units. Performs unit conversions if necessary.
2027 * @param[in] rhs right-hand side unit for the comparison
2028 * @returns true IFF the value of `this` is less than the value of `rhs`
2029 */
2030 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs>
2031 inline constexpr bool operator<(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) const noexcept
2032 {
2033 return (nls::m_value < units::convert<UnitsRhs, Units>(rhs.m_value));
2034 }
2035
2036 /**
2037 * @brief less-than or equal
2038 * @details compares the linearized value of two units. Performs unit conversions if necessary.
2039 * @param[in] rhs right-hand side unit for the comparison
2040 * @returns true IFF the value of `this` is less than or equal to the value of `rhs`
2041 */
2042 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs>
2043 inline constexpr bool operator<=(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) const noexcept
2044 {
2045 return (nls::m_value <= units::convert<UnitsRhs, Units>(rhs.m_value));
2046 }
2047
2048 /**
2049 * @brief greater-than
2050 * @details compares the linearized value of two units. Performs unit conversions if necessary.
2051 * @param[in] rhs right-hand side unit for the comparison
2052 * @returns true IFF the value of `this` is greater than the value of `rhs`
2053 */
2054 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs>
2055 inline constexpr bool operator>(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) const noexcept
2056 {
2057 return (nls::m_value > units::convert<UnitsRhs, Units>(rhs.m_value));
2058 }
2059
2060 /**
2061 * @brief greater-than or equal
2062 * @details compares the linearized value of two units. Performs unit conversions if necessary.
2063 * @param[in] rhs right-hand side unit for the comparison
2064 * @returns true IFF the value of `this` is greater than or equal to the value of `rhs`
2065 */
2066 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs>
2067 inline constexpr bool operator>=(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) const noexcept
2068 {
2069 return (nls::m_value >= units::convert<UnitsRhs, Units>(rhs.m_value));
2070 }
2071
2072 /**
2073 * @brief equality
2074 * @details compares the linearized value of two units. Performs unit conversions if necessary.
2075 * @param[in] rhs right-hand side unit for the comparison
2076 * @returns true IFF the value of `this` exactly equal to the value of rhs.
2077 * @note This may not be suitable for all applications when the underlying_type of unit_t is a double.
2078 */
2079 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs, std::enable_if_t<std::is_floating_point<T>::value || std::is_floating_point<Ty>::value, int> = 0>
2080 inline constexpr bool operator==(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) const noexcept
2081 {
2082 return detail::abs(nls::m_value - units::convert<UnitsRhs, Units>(rhs.m_value)) < std::numeric_limits<T>::epsilon() *
2083 detail::abs(nls::m_value + units::convert<UnitsRhs, Units>(rhs.m_value)) ||
2084 detail::abs(nls::m_value - units::convert<UnitsRhs, Units>(rhs.m_value)) < (std::numeric_limits<T>::min)();
2085 }
2086
2087 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs, std::enable_if_t<std::is_integral<T>::value && std::is_integral<Ty>::value, int> = 0>
2088 inline constexpr bool operator==(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) const noexcept
2089 {
2090 return nls::m_value == units::convert<UnitsRhs, Units>(rhs.m_value);
2091 }
2092
2093 /**
2094 * @brief inequality
2095 * @details compares the linearized value of two units. Performs unit conversions if necessary.
2096 * @param[in] rhs right-hand side unit for the comparison
2097 * @returns true IFF the value of `this` is not equal to the value of rhs.
2098 * @note This may not be suitable for all applications when the underlying_type of unit_t is a double.
2099 */
2100 template<class UnitsRhs, typename Ty, template<typename> class NlsRhs>
2101 inline constexpr bool operator!=(const unit_t<UnitsRhs, Ty, NlsRhs>& rhs) const noexcept
2102 {
2103 return !(*this == rhs);
2104 }
2105
2106 /**
2107 * @brief unit value
2108 * @returns value of the unit in it's underlying, non-safe type.
2109 */
2110 inline constexpr underlying_type value() const noexcept
2111 {
2112 return static_cast<underlying_type>(*this);
2113 }
2114
2115 /**
2116 * @brief unit value
2117 * @returns value of the unit converted to an arithmetic, non-safe type.
2118 */
2119 template<typename Ty, class = std::enable_if_t<std::is_arithmetic<Ty>::value>>
2120 inline constexpr Ty to() const noexcept
2121 {
2122 return static_cast<Ty>(*this);
2123 }
2124
2125 /**
2126 * @brief linearized unit value
2127 * @returns linearized value of unit which has a non-linear scale. For `unit_t` types with
2128 * linear scales, this is equivalent to `value`.
2129 */
2130 template<typename Ty, class = std::enable_if_t<std::is_arithmetic<Ty>::value>>
2131 inline constexpr Ty toLinearized() const noexcept
2132 {
2133 return static_cast<Ty>(m_value);
2134 }
2135
2136 /**
2137 * @brief conversion
2138 * @details Converts to a different unit container. Units can be converted to other containers
2139 * implicitly, but this can be used in cases where explicit notation of a conversion
2140 * is beneficial, or where an r-value container is needed.
2141 * @tparam U unit (not unit_t) to convert to
2142 * @returns a unit container with the specified units containing the equivalent value to
2143 * *this.
2144 */
2145 template<class U>
2146 inline constexpr unit_t<U> convert() const noexcept
2147 {
2148 static_assert(traits::is_unit<U>::value, "Template parameter `U` must be a unit type.");
2149 return unit_t<U>(*this);
2150 }
2151
2152 /**
2153 * @brief implicit type conversion.
2154 * @details only enabled for scalar unit types.
2155 */
2156 template<class Ty, std::enable_if_t<traits::is_dimensionless_unit<Units>::value && std::is_arithmetic<Ty>::value, int> = 0>
2157 inline constexpr operator Ty() const noexcept
2158 {
2159 // this conversion also resolves any PI exponents, by converting from a non-zero PI ratio to a zero-pi ratio.
2160 return static_cast<Ty>(units::convert<Units, unit<std::ratio<1>, units::category::scalar_unit>>((*this)()));
2161 }
2162
2163 /**
2164 * @brief explicit type conversion.
2165 * @details only enabled for non-dimensionless unit types.
2166 */
2167 template<class Ty, std::enable_if_t<!traits::is_dimensionless_unit<Units>::value && std::is_arithmetic<Ty>::value, int> = 0>
2168 inline constexpr explicit operator Ty() const noexcept
2169 {
2170 return static_cast<Ty>((*this)());
2171 }
2172
2173 /**
2174 * @brief chrono implicit type conversion.
2175 * @details only enabled for time unit types.
2176 */
2177 template<typename U = Units, std::enable_if_t<units::traits::is_convertible_unit<U, unit<std::ratio<1>, category::time_unit>>::value, int> = 0>
2178 inline constexpr operator std::chrono::nanoseconds() const noexcept
2179 {
2180 return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::duration<double, std::nano>(units::convert<Units, unit<std::ratio<1,1000000000>, category::time_unit>>((*this)())));
2181 }
2182
2183 /**
2184 * @brief returns the unit name
2185 */
2186 inline constexpr const char* name() const noexcept
2187 {
2188 return units::name(*this);
2189 }
2190
2191 /**
2192 * @brief returns the unit abbreviation
2193 */
2194 inline constexpr const char* abbreviation() const noexcept
2195 {
2196 return units::abbreviation(*this);
2197 }
2198
2199 public:
2200
2201 template<class U, typename Ty, template<typename> class Nlt>
2202 friend class unit_t;
2203 };
2204
2205 //------------------------------
2206 // UNIT_T NON-MEMBER FUNCTIONS
2207 //------------------------------
2208
2209 /**
2210 * @ingroup UnitContainers
2211 * @brief Constructs a unit container from an arithmetic type.
2212 * @details make_unit can be used to construct a unit container from an arithmetic type, as an alternative to
2213 * using the explicit constructor. Unlike the explicit constructor it forces the user to explicitly
2214 * specify the units.
2215 * @tparam UnitType Type to construct.
2216 * @tparam Ty Arithmetic type.
2217 * @param[in] value Arithmetic value that represents a quantity in units of `UnitType`.
2218 */
2219 template<class UnitType, typename T, class = std::enable_if_t<std::is_arithmetic<T>::value>>
2220 inline constexpr UnitType make_unit(const T value) noexcept
2221 {
2222 static_assert(traits::is_unit_t<UnitType>::value, "Template parameter `UnitType` must be a unit type (_t).");
2223
2224 return UnitType(value);
2225 }
2226
2227#if defined(UNIT_LIB_ENABLE_IOSTREAM)
2228 template<class Units, typename T, template<typename> class NonLinearScale>
2229 inline std::ostream& operator<<(std::ostream& os, const unit_t<Units, T, NonLinearScale>& obj) noexcept
2230 {
2231 using BaseUnits = unit<std::ratio<1>, typename traits::unit_traits<Units>::base_unit_type>;
2232 os << convert<Units, BaseUnits>(obj());
2233
2234 if (traits::unit_traits<Units>::base_unit_type::meter_ratio::num != 0) { os << " m"; }
2235 if (traits::unit_traits<Units>::base_unit_type::meter_ratio::num != 0 &&
2236 traits::unit_traits<Units>::base_unit_type::meter_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::meter_ratio::num; }
2237 if (traits::unit_traits<Units>::base_unit_type::meter_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::meter_ratio::den; }
2238
2239 if (traits::unit_traits<Units>::base_unit_type::kilogram_ratio::num != 0) { os << " kg"; }
2240 if (traits::unit_traits<Units>::base_unit_type::kilogram_ratio::num != 0 &&
2241 traits::unit_traits<Units>::base_unit_type::kilogram_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::kilogram_ratio::num; }
2242 if (traits::unit_traits<Units>::base_unit_type::kilogram_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::kilogram_ratio::den; }
2243
2244 if (traits::unit_traits<Units>::base_unit_type::second_ratio::num != 0) { os << " s"; }
2245 if (traits::unit_traits<Units>::base_unit_type::second_ratio::num != 0 &&
2246 traits::unit_traits<Units>::base_unit_type::second_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::second_ratio::num; }
2247 if (traits::unit_traits<Units>::base_unit_type::second_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::second_ratio::den; }
2248
2249 if (traits::unit_traits<Units>::base_unit_type::ampere_ratio::num != 0) { os << " A"; }
2250 if (traits::unit_traits<Units>::base_unit_type::ampere_ratio::num != 0 &&
2251 traits::unit_traits<Units>::base_unit_type::ampere_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::ampere_ratio::num; }
2252 if (traits::unit_traits<Units>::base_unit_type::ampere_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::ampere_ratio::den; }
2253
2254 if (traits::unit_traits<Units>::base_unit_type::kelvin_ratio::num != 0) { os << " K"; }
2255 if (traits::unit_traits<Units>::base_unit_type::kelvin_ratio::num != 0 &&
2256 traits::unit_traits<Units>::base_unit_type::kelvin_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::kelvin_ratio::num; }
2257 if (traits::unit_traits<Units>::base_unit_type::kelvin_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::kelvin_ratio::den; }
2258
2259 if (traits::unit_traits<Units>::base_unit_type::mole_ratio::num != 0) { os << " mol"; }
2260 if (traits::unit_traits<Units>::base_unit_type::mole_ratio::num != 0 &&
2261 traits::unit_traits<Units>::base_unit_type::mole_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::mole_ratio::num; }
2262 if (traits::unit_traits<Units>::base_unit_type::mole_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::mole_ratio::den; }
2263
2264 if (traits::unit_traits<Units>::base_unit_type::candela_ratio::num != 0) { os << " cd"; }
2265 if (traits::unit_traits<Units>::base_unit_type::candela_ratio::num != 0 &&
2266 traits::unit_traits<Units>::base_unit_type::candela_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::candela_ratio::num; }
2267 if (traits::unit_traits<Units>::base_unit_type::candela_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::candela_ratio::den; }
2268
2269 if (traits::unit_traits<Units>::base_unit_type::radian_ratio::num != 0) { os << " rad"; }
2270 if (traits::unit_traits<Units>::base_unit_type::radian_ratio::num != 0 &&
2271 traits::unit_traits<Units>::base_unit_type::radian_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::radian_ratio::num; }
2272 if (traits::unit_traits<Units>::base_unit_type::radian_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::radian_ratio::den; }
2273
2274 if (traits::unit_traits<Units>::base_unit_type::byte_ratio::num != 0) { os << " b"; }
2275 if (traits::unit_traits<Units>::base_unit_type::byte_ratio::num != 0 &&
2276 traits::unit_traits<Units>::base_unit_type::byte_ratio::num != 1) { os << "^" << traits::unit_traits<Units>::base_unit_type::byte_ratio::num; }
2277 if (traits::unit_traits<Units>::base_unit_type::byte_ratio::den != 1) { os << "/" << traits::unit_traits<Units>::base_unit_type::byte_ratio::den; }
2278
2279 return os;
2280 }
2281#endif
2282
2283 template<class Units, typename T, template<typename> class NonLinearScale, typename RhsType>
2285 {
2287 (traits::is_dimensionless_unit<decltype(lhs)>::value && std::is_arithmetic<RhsType>::value),
2288 "parameters are not compatible units.");
2289
2290 lhs = lhs + rhs;
2291 return lhs;
2292 }
2293
2294 template<class Units, typename T, template<typename> class NonLinearScale, typename RhsType>
2296 {
2298 (traits::is_dimensionless_unit<decltype(lhs)>::value && std::is_arithmetic<RhsType>::value),
2299 "parameters are not compatible units.");
2300
2301 lhs = lhs - rhs;
2302 return lhs;
2303 }
2304
2305 template<class Units, typename T, template<typename> class NonLinearScale, typename RhsType>
2307 {
2308 static_assert((traits::is_dimensionless_unit<RhsType>::value || std::is_arithmetic<RhsType>::value),
2309 "right-hand side parameter must be dimensionless.");
2310
2311 lhs = lhs * rhs;
2312 return lhs;
2313 }
2314
2315 template<class Units, typename T, template<typename> class NonLinearScale, typename RhsType>
2317 {
2318 static_assert((traits::is_dimensionless_unit<RhsType>::value || std::is_arithmetic<RhsType>::value),
2319 "right-hand side parameter must be dimensionless.");
2320
2321 lhs = lhs / rhs;
2322 return lhs;
2323 }
2324
2325 //------------------------------
2326 // UNIT_T UNARY OPERATORS
2327 //------------------------------
2328
2329 // unary addition: +T
2330 template<class Units, typename T, template<typename> class NonLinearScale>
2332 {
2333 return u;
2334 }
2335
2336 // prefix increment: ++T
2337 template<class Units, typename T, template<typename> class NonLinearScale>
2339 {
2341 return u;
2342 }
2343
2344 // postfix increment: T++
2345 template<class Units, typename T, template<typename> class NonLinearScale>
2347 {
2348 auto ret = u;
2350 return ret;
2351 }
2352
2353 // unary addition: -T
2354 template<class Units, typename T, template<typename> class NonLinearScale>
2356 {
2358 }
2359
2360 // prefix increment: --T
2361 template<class Units, typename T, template<typename> class NonLinearScale>
2363 {
2365 return u;
2366 }
2367
2368 // postfix increment: T--
2369 template<class Units, typename T, template<typename> class NonLinearScale>
2371 {
2372 auto ret = u;
2374 return ret;
2375 }
2376
2377 //------------------------------
2378 // UNIT_CAST
2379 //------------------------------
2380
2381 /**
2382 * @ingroup Conversion
2383 * @brief Casts a unit container to an arithmetic type.
2384 * @details unit_cast can be used to remove the strong typing from a unit class, and convert it
2385 * to a built-in arithmetic type. This may be useful for compatibility with libraries
2386 * and legacy code that don't support `unit_t` types. E.g
2387 * @code meter_t unitVal(5);
2388 * double value = units::unit_cast<double>(unitVal); // value = 5.0
2389 * @endcode
2390 * @tparam T Type to cast the unit type to. Must be a built-in arithmetic type.
2391 * @param value Unit value to cast.
2392 * @sa unit_t::to
2393 */
2394 template<typename T, typename Units, class = std::enable_if_t<std::is_arithmetic<T>::value && traits::is_unit_t<Units>::value>>
2395 inline constexpr T unit_cast(const Units& value) noexcept
2396 {
2397 return static_cast<T>(value);
2398 }
2399
2400 //------------------------------
2401 // NON-LINEAR SCALE TRAITS
2402 //------------------------------
2403
2404 // forward declaration
2405 template<typename T> struct decibel_scale;
2406
2407 namespace traits
2408 {
2409 /**
2410 * @ingroup TypeTraits
2411 * @brief Trait which tests whether a type is inherited from a linear scale.
2412 * @details Inherits from `std::true_type` or `std::false_type`. Use `has_linear_scale<U1 [, U2, ...]>::value` to test
2413 * one or more types to see if they represent unit_t's whose scale is linear.
2414 * @tparam T one or more types to test.
2415 */
2416#if !defined(_MSC_VER) || _MSC_VER > 1800 // bug in VS2013 prevents this from working
2417 template<typename... T>
2418 struct has_linear_scale : std::integral_constant<bool, units::all_true<std::is_base_of<units::linear_scale<typename units::traits::unit_t_traits<T>::underlying_type>, T>::value...>::value > {};
2419 template<typename... T>
2420 inline constexpr bool has_linear_scale_v = has_linear_scale<T...>::value;
2421#else
2422 template<typename T1, typename T2 = T1, typename T3 = T1>
2423 struct has_linear_scale : std::integral_constant<bool,
2424 std::is_base_of<units::linear_scale<typename units::traits::unit_t_traits<T1>::underlying_type>, T1>::value &&
2425 std::is_base_of<units::linear_scale<typename units::traits::unit_t_traits<T2>::underlying_type>, T2>::value &&
2426 std::is_base_of<units::linear_scale<typename units::traits::unit_t_traits<T3>::underlying_type>, T3>::value> {};
2427 template<typename T1, typename T2 = T1, typename T3 = T1>
2428 inline constexpr bool has_linear_scale_v = has_linear_scale<T1, T2, T3>::value;
2429#endif
2430
2431 /**
2432 * @ingroup TypeTraits
2433 * @brief Trait which tests whether a type is inherited from a decibel scale.
2434 * @details Inherits from `std::true_type` or `std::false_type`. Use `has_decibel_scale<U1 [, U2, ...]>::value` to test
2435 * one or more types to see if they represent unit_t's whose scale is in decibels.
2436 * @tparam T one or more types to test.
2437 */
2438#if !defined(_MSC_VER) || _MSC_VER > 1800 // bug in VS2013 prevents this from working
2439 template<typename... T>
2440 struct has_decibel_scale : std::integral_constant<bool, units::all_true<std::is_base_of<units::decibel_scale<typename units::traits::unit_t_traits<T>::underlying_type>, T>::value...>::value> {};
2441 template<typename... T>
2442 inline constexpr bool has_decibel_scale_v = has_decibel_scale<T...>::value;
2443#else
2444 template<typename T1, typename T2 = T1, typename T3 = T1>
2445 struct has_decibel_scale : std::integral_constant<bool,
2446 std::is_base_of<units::decibel_scale<typename units::traits::unit_t_traits<T1>::underlying_type>, T1>::value &&
2447 std::is_base_of<units::decibel_scale<typename units::traits::unit_t_traits<T2>::underlying_type>, T2>::value &&
2448 std::is_base_of<units::decibel_scale<typename units::traits::unit_t_traits<T2>::underlying_type>, T3>::value> {};
2449 template<typename T1, typename T2 = T1, typename T3 = T1>
2450 inline constexpr bool has_decibel_scale_v = has_decibel_scale<T1, T2, T3>::value;
2451#endif
2452
2453 /**
2454 * @ingroup TypeTraits
2455 * @brief Trait which tests whether two types has the same non-linear scale.
2456 * @details Inherits from `std::true_type` or `std::false_type`. Use `is_same_scale<U1 , U2>::value` to test
2457 * whether two types have the same non-linear scale.
2458 * @tparam T1 left hand type.
2459 * @tparam T2 right hand type
2460 */
2461 template<typename T1, typename T2>
2462 struct is_same_scale : std::integral_constant<bool,
2463 std::is_same<typename units::traits::unit_t_traits<T1>::non_linear_scale_type, typename units::traits::unit_t_traits<T2>::non_linear_scale_type>::value>
2464 {};
2465 template<typename T1, typename T2>
2467 }
2468
2469 //----------------------------------
2470 // NON-LINEAR SCALES
2471 //----------------------------------
2472
2473 // Non-linear transforms are used to pre and post scale units which are defined in terms of non-
2474 // linear functions of their current value. A good example of a non-linear scale would be a
2475 // logarithmic or decibel scale
2476
2477 //------------------------------
2478 // LINEAR SCALE
2479 //------------------------------
2480
2481 /**
2482 * @brief unit_t scale which is linear
2483 * @details Represents units on a linear scale. This is the appropriate unit_t scale for almost
2484 * all units almost all of the time.
2485 * @tparam T underlying storage type
2486 * @sa unit_t
2487 */
2488 template<typename T>
2490 {
2491 inline constexpr linear_scale() = default; ///< default constructor.
2492 inline constexpr linear_scale(const linear_scale&) = default;
2493 inline ~linear_scale() = default;
2494 inline linear_scale& operator=(const linear_scale&) = default;
2495#if defined(_MSC_VER) && (_MSC_VER > 1800)
2496 inline constexpr linear_scale(linear_scale&&) = default;
2497 inline linear_scale& operator=(linear_scale&&) = default;
2498#endif
2499 template<class... Args>
2500 inline constexpr linear_scale(const T& value, Args&&...) noexcept : m_value(value) {} ///< constructor.
2501 inline constexpr T operator()() const noexcept { return m_value; } ///< returns value.
2502
2503 T m_value; ///< linearized value.
2504 };
2505
2506 //----------------------------------
2507 // SCALAR (LINEAR) UNITS
2508 //----------------------------------
2509
2510 // Scalar units are the *ONLY* units implicitly convertible to/from built-in types.
2512 {
2515
2518 }
2519
2520// ignore the redeclaration of the default template parameters
2521#if defined(_MSC_VER)
2522# pragma warning(push)
2523# pragma warning(disable : 4348)
2524#endif
2527#if defined(_MSC_VER)
2528# pragma warning(pop)
2529#endif
2530
2531 //------------------------------
2532 // LINEAR ARITHMETIC
2533 //------------------------------
2534
2535 template<class UnitTypeLhs, class UnitTypeRhs, std::enable_if_t<!traits::is_same_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
2536 constexpr inline int operator+(const UnitTypeLhs& /* lhs */, const UnitTypeRhs& /* rhs */) noexcept
2537 {
2538 static_assert(traits::is_same_scale<UnitTypeLhs, UnitTypeRhs>::value, "Cannot add units with different linear/non-linear scales.");
2539 return 0;
2540 }
2541
2542 /// Addition operator for unit_t types with a linear_scale.
2543 template<class UnitTypeLhs, class UnitTypeRhs, std::enable_if_t<traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
2544 inline constexpr UnitTypeLhs operator+(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept
2545 {
2546 using UnitsLhs = typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type;
2547 using UnitsRhs = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2548 return UnitTypeLhs(lhs() + convert<UnitsRhs, UnitsLhs>(rhs()));
2549 }
2550
2551 /// Addition operator for scalar unit_t types with a linear_scale. Scalar types can be implicitly converted to built-in types.
2552 template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
2553 inline constexpr dimensionless::scalar_t operator+(const dimensionless::scalar_t& lhs, T rhs) noexcept
2554 {
2555 return dimensionless::scalar_t(lhs() + rhs);
2556 }
2557
2558 /// Addition operator for scalar unit_t types with a linear_scale. Scalar types can be implicitly converted to built-in types.
2559 template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
2560 inline constexpr dimensionless::scalar_t operator+(T lhs, const dimensionless::scalar_t& rhs) noexcept
2561 {
2562 return dimensionless::scalar_t(lhs + rhs());
2563 }
2564
2565 /// Subtraction operator for unit_t types with a linear_scale.
2566 template<class UnitTypeLhs, class UnitTypeRhs, std::enable_if_t<traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
2567 inline constexpr UnitTypeLhs operator-(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept
2568 {
2569 using UnitsLhs = typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type;
2570 using UnitsRhs = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2571 return UnitTypeLhs(lhs() - convert<UnitsRhs, UnitsLhs>(rhs()));
2572 }
2573
2574 /// Subtraction operator for scalar unit_t types with a linear_scale. Scalar types can be implicitly converted to built-in types.
2575 template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
2576 inline constexpr dimensionless::scalar_t operator-(const dimensionless::scalar_t& lhs, T rhs) noexcept
2577 {
2578 return dimensionless::scalar_t(lhs() - rhs);
2579 }
2580
2581 /// Subtraction operator for scalar unit_t types with a linear_scale. Scalar types can be implicitly converted to built-in types.
2582 template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
2583 inline constexpr dimensionless::scalar_t operator-(T lhs, const dimensionless::scalar_t& rhs) noexcept
2584 {
2585 return dimensionless::scalar_t(lhs - rhs());
2586 }
2587
2588 /// Multiplication type for convertible unit_t types with a linear scale. @returns the multiplied value, with the same type as left-hand side unit.
2589 template<class UnitTypeLhs, class UnitTypeRhs,
2590 std::enable_if_t<traits::is_convertible_unit_t<UnitTypeLhs, UnitTypeRhs>::value && traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
2591 inline constexpr auto operator*(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept -> unit_t<compound_unit<squared<typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type>>>
2592 {
2593 using UnitsLhs = typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type;
2594 using UnitsRhs = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2596 (lhs() * convert<UnitsRhs, UnitsLhs>(rhs()));
2597 }
2598
2599 /// Multiplication type for non-convertible unit_t types with a linear scale. @returns the multiplied value, whose type is a compound unit of the left and right hand side values.
2600 template<class UnitTypeLhs, class UnitTypeRhs,
2601 std::enable_if_t<!traits::is_convertible_unit_t<UnitTypeLhs, UnitTypeRhs>::value && traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value && !traits::is_dimensionless_unit<UnitTypeLhs>::value && !traits::is_dimensionless_unit<UnitTypeRhs>::value, int> = 0>
2602 inline constexpr auto operator*(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept -> unit_t<compound_unit<typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type, typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type>>
2603 {
2604 using UnitsLhs = typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type;
2605 using UnitsRhs = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2606 return unit_t<compound_unit<UnitsLhs, UnitsRhs>>
2607 (lhs() * rhs());
2608 }
2609
2610 /// Multiplication by a dimensionless unit for unit_t types with a linear scale.
2611 template<class UnitTypeLhs, typename UnitTypeRhs,
2612 std::enable_if_t<traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value && !traits::is_dimensionless_unit<UnitTypeLhs>::value && traits::is_dimensionless_unit<UnitTypeRhs>::value, int> = 0>
2613 inline constexpr UnitTypeLhs operator*(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept
2614 {
2615 // the cast makes sure factors of PI are handled as expected
2616 return UnitTypeLhs(lhs() * static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs));
2617 }
2618
2619 /// Multiplication by a dimensionless unit for unit_t types with a linear scale.
2620 template<class UnitTypeLhs, typename UnitTypeRhs,
2621 std::enable_if_t<traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value && traits::is_dimensionless_unit<UnitTypeLhs>::value && !traits::is_dimensionless_unit<UnitTypeRhs>::value, int> = 0>
2622 inline constexpr UnitTypeRhs operator*(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept
2623 {
2624 // the cast makes sure factors of PI are handled as expected
2625 return UnitTypeRhs(static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs) * rhs());
2626 }
2627
2628 /// Multiplication by a scalar for unit_t types with a linear scale.
2629 template<class UnitTypeLhs, typename T,
2630 std::enable_if_t<std::is_arithmetic<T>::value && traits::has_linear_scale<UnitTypeLhs>::value, int> = 0>
2631 inline constexpr UnitTypeLhs operator*(const UnitTypeLhs& lhs, T rhs) noexcept
2632 {
2633 return UnitTypeLhs(lhs() * rhs);
2634 }
2635
2636 /// Multiplication by a scalar for unit_t types with a linear scale.
2637 template<class UnitTypeRhs, typename T,
2638 std::enable_if_t<std::is_arithmetic<T>::value && traits::has_linear_scale<UnitTypeRhs>::value, int> = 0>
2639 inline constexpr UnitTypeRhs operator*(T lhs, const UnitTypeRhs& rhs) noexcept
2640 {
2641 return UnitTypeRhs(lhs * rhs());
2642 }
2643
2644 /// Division for convertible unit_t types with a linear scale. @returns the lhs divided by rhs value, whose type is a scalar
2645 template<class UnitTypeLhs, class UnitTypeRhs,
2646 std::enable_if_t<traits::is_convertible_unit_t<UnitTypeLhs, UnitTypeRhs>::value && traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
2647 inline constexpr dimensionless::scalar_t operator/(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept
2648 {
2649 using UnitsLhs = typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type;
2650 using UnitsRhs = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2651 return dimensionless::scalar_t(lhs() / convert<UnitsRhs, UnitsLhs>(rhs()));
2652 }
2653
2654 /// Division for non-convertible unit_t types with a linear scale. @returns the lhs divided by the rhs, with a compound unit type of lhs/rhs
2655 template<class UnitTypeLhs, class UnitTypeRhs,
2656 std::enable_if_t<!traits::is_convertible_unit_t<UnitTypeLhs, UnitTypeRhs>::value && traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value && !traits::is_dimensionless_unit<UnitTypeLhs>::value && !traits::is_dimensionless_unit<UnitTypeRhs>::value, int> = 0>
2658 {
2659 using UnitsLhs = typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type;
2660 using UnitsRhs = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2662 (lhs() / rhs());
2663 }
2664
2665 /// Division by a dimensionless unit for unit_t types with a linear scale
2666 template<class UnitTypeLhs, class UnitTypeRhs,
2667 std::enable_if_t<traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value && !traits::is_dimensionless_unit<UnitTypeLhs>::value && traits::is_dimensionless_unit<UnitTypeRhs>::value, int> = 0>
2668 inline constexpr UnitTypeLhs operator/(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept
2669 {
2670 return UnitTypeLhs(lhs() / static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs));
2671 }
2672
2673 /// Division of a dimensionless unit by a unit_t type with a linear scale
2674 template<class UnitTypeLhs, class UnitTypeRhs,
2675 std::enable_if_t<traits::has_linear_scale<UnitTypeLhs, UnitTypeRhs>::value && traits::is_dimensionless_unit<UnitTypeLhs>::value && !traits::is_dimensionless_unit<UnitTypeRhs>::value, int> = 0>
2676 inline constexpr auto operator/(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept -> unit_t<inverse<typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type>>
2677 {
2679 (static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs) / rhs());
2680 }
2681
2682 /// Division by a scalar for unit_t types with a linear scale
2683 template<class UnitTypeLhs, typename T,
2684 std::enable_if_t<std::is_arithmetic<T>::value && traits::has_linear_scale<UnitTypeLhs>::value, int> = 0>
2685 inline constexpr UnitTypeLhs operator/(const UnitTypeLhs& lhs, T rhs) noexcept
2686 {
2687 return UnitTypeLhs(lhs() / rhs);
2688 }
2689
2690 /// Division of a scalar by a unit_t type with a linear scale
2691 template<class UnitTypeRhs, typename T,
2692 std::enable_if_t<std::is_arithmetic<T>::value && traits::has_linear_scale<UnitTypeRhs>::value, int> = 0>
2693 inline constexpr auto operator/(T lhs, const UnitTypeRhs& rhs) noexcept -> unit_t<inverse<typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type>>
2694 {
2695 using UnitsRhs = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2697 (lhs / rhs());
2698 }
2699
2700 //----------------------------------
2701 // SCALAR COMPARISONS
2702 //----------------------------------
2703
2704 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2705 constexpr bool operator==(const UNIT_LIB_DEFAULT_TYPE lhs, const Units& rhs) noexcept
2706 {
2707 return detail::abs(lhs - static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs)) < std::numeric_limits<UNIT_LIB_DEFAULT_TYPE>::epsilon() * detail::abs(lhs + static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs)) ||
2709 }
2710
2711 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2712 constexpr bool operator==(const Units& lhs, const UNIT_LIB_DEFAULT_TYPE rhs) noexcept
2713 {
2714 return detail::abs(static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs) - rhs) < std::numeric_limits<UNIT_LIB_DEFAULT_TYPE>::epsilon() * detail::abs(static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs) + rhs) ||
2716 }
2717
2718 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2719 constexpr bool operator!=(const UNIT_LIB_DEFAULT_TYPE lhs, const Units& rhs) noexcept
2720 {
2721 return!(lhs == static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs));
2722 }
2723
2724 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2725 constexpr bool operator!=(const Units& lhs, const UNIT_LIB_DEFAULT_TYPE rhs) noexcept
2726 {
2727 return !(static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs) == rhs);
2728 }
2729
2730 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2731 constexpr bool operator>=(const UNIT_LIB_DEFAULT_TYPE lhs, const Units& rhs) noexcept
2732 {
2733 return std::isgreaterequal(lhs, static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs));
2734 }
2735
2736 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2737 constexpr bool operator>=(const Units& lhs, const UNIT_LIB_DEFAULT_TYPE rhs) noexcept
2738 {
2739 return std::isgreaterequal(static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs), rhs);
2740 }
2741
2742 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2743 constexpr bool operator>(const UNIT_LIB_DEFAULT_TYPE lhs, const Units& rhs) noexcept
2744 {
2745 return lhs > static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs);
2746 }
2747
2748 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2749 constexpr bool operator>(const Units& lhs, const UNIT_LIB_DEFAULT_TYPE rhs) noexcept
2750 {
2751 return static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs) > rhs;
2752 }
2753
2754 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2755 constexpr bool operator<=(const UNIT_LIB_DEFAULT_TYPE lhs, const Units& rhs) noexcept
2756 {
2757 return std::islessequal(lhs, static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs));
2758 }
2759
2760 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2761 constexpr bool operator<=(const Units& lhs, const UNIT_LIB_DEFAULT_TYPE rhs) noexcept
2762 {
2763 return std::islessequal(static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs), rhs);
2764 }
2765
2766 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2767 constexpr bool operator<(const UNIT_LIB_DEFAULT_TYPE lhs, const Units& rhs) noexcept
2768 {
2769 return lhs < static_cast<UNIT_LIB_DEFAULT_TYPE>(rhs);
2770 }
2771
2772 template<typename Units, class = std::enable_if_t<units::traits::is_dimensionless_unit<Units>::value>>
2773 constexpr bool operator<(const Units& lhs, const UNIT_LIB_DEFAULT_TYPE rhs) noexcept
2774 {
2775 return static_cast<UNIT_LIB_DEFAULT_TYPE>(lhs) < rhs;
2776 }
2777
2778 //----------------------------------
2779 // POW
2780 //----------------------------------
2781
2782 /** @cond */ // DOXYGEN IGNORE
2783 namespace detail
2784 {
2785 /// recursive exponential implementation
2786 template <int N, class U> struct power_of_unit
2787 {
2788 typedef typename units::detail::unit_multiply<U, typename power_of_unit<N - 1, U>::type> type;
2789 };
2790
2791 /// End recursion
2792 template <class U> struct power_of_unit<1, U>
2793 {
2794 typedef U type;
2795 };
2796 }
2797 /** @endcond */ // END DOXYGEN IGNORE
2798
2799 namespace math
2800 {
2801 /**
2802 * @brief computes the value of <i>value</i> raised to the <i>power</i>
2803 * @details Only implemented for linear_scale units. <i>Power</i> must be known at compile time, so the resulting unit type can be deduced.
2804 * @tparam power exponential power to raise <i>value</i> by.
2805 * @param[in] value `unit_t` derived type to raise to the given <i>power</i>
2806 * @returns new unit_t, raised to the given exponent
2807 */
2808 template<int power, class UnitType, class = typename std::enable_if<traits::has_linear_scale<UnitType>::value, int>>
2809 inline constexpr auto pow(const UnitType& value) noexcept -> unit_t<typename units::detail::power_of_unit<power, typename units::traits::unit_t_traits<UnitType>::unit_type>::type, typename units::traits::unit_t_traits<UnitType>::underlying_type, linear_scale>
2810 {
2812 (gcem::pow(value(), power));
2813 }
2814
2815 /**
2816 * @brief computes the value of <i>value</i> raised to the <i>power</i> as a constexpr
2817 * @details Only implemented for linear_scale units. <i>Power</i> must be known at compile time, so the resulting unit type can be deduced.
2818 * Additionally, the power must be <i>a positive, integral, value</i>.
2819 * @tparam power exponential power to raise <i>value</i> by.
2820 * @param[in] value `unit_t` derived type to raise to the given <i>power</i>
2821 * @returns new unit_t, raised to the given exponent
2822 */
2823 template<int power, class UnitType, class = typename std::enable_if<traits::has_linear_scale<UnitType>::value, int>>
2824 inline constexpr auto cpow(const UnitType& value) noexcept -> unit_t<typename units::detail::power_of_unit<power, typename units::traits::unit_t_traits<UnitType>::unit_type>::type, typename units::traits::unit_t_traits<UnitType>::underlying_type, linear_scale>
2825 {
2826 static_assert(power >= 0, "cpow cannot accept negative numbers. Try units::math::pow instead.");
2828 (detail::pow(value(), power));
2829 }
2830 }
2831
2832 //------------------------------
2833 // DECIBEL SCALE
2834 //------------------------------
2835
2836 /**
2837 * @brief unit_t scale for representing decibel values.
2838 * @details internally stores linearized values. `operator()` returns the value in dB.
2839 * @tparam T underlying storage type
2840 * @sa unit_t
2841 */
2842 template<typename T>
2844 {
2845 inline constexpr decibel_scale() = default;
2846 inline constexpr decibel_scale(const decibel_scale&) = default;
2847 inline ~decibel_scale() = default;
2848 inline decibel_scale& operator=(const decibel_scale&) = default;
2849#if defined(_MSC_VER) && (_MSC_VER > 1800)
2850 inline constexpr decibel_scale(decibel_scale&&) = default;
2851 inline decibel_scale& operator=(decibel_scale&&) = default;
2852#endif
2853 inline constexpr decibel_scale(const T value) noexcept : m_value(std::pow(10, value / 10)) {}
2854 template<class... Args>
2855 inline constexpr decibel_scale(const T value, std::true_type, Args&&...) noexcept : m_value(value) {}
2856 inline constexpr T operator()() const noexcept { return 10 * std::log10(m_value); }
2857
2858 T m_value; ///< linearized value
2859 };
2860
2861 //------------------------------
2862 // SCALAR (DECIBEL) UNITS
2863 //------------------------------
2864
2865 /**
2866 * @brief namespace for unit types and containers for units that have no dimension (scalar units)
2867 * @sa See unit_t for more information on unit type containers.
2868 */
2869 namespace dimensionless
2870 {
2872 typedef dB_t dBi_t;
2873 }
2874#if defined(UNIT_LIB_ENABLE_IOSTREAM)
2875 namespace dimensionless
2876 {
2877 inline std::ostream& operator<<(std::ostream& os, const dB_t& obj) { os << obj() << " dB"; return os; }
2878 }
2879#endif
2880}
2881#if __has_include(<fmt/format.h>) && !defined(UNIT_LIB_DISABLE_FMT)
2882template <>
2883struct fmt::formatter<units::dimensionless::dB_t> : fmt::formatter<double>
2884{
2885 template <typename FmtContext>
2886 auto format(
2887 const units::dimensionless::dB_t& obj,
2888 FmtContext& ctx) const
2889 {
2890 auto out = ctx.out();
2891 out = fmt::formatter<double>::format(obj(), ctx);
2892 return fmt::format_to(out, " dB");
2893 }
2894};
2895#endif
2896
2897namespace units {
2898 //------------------------------
2899 // DECIBEL ARITHMETIC
2900 //------------------------------
2901
2902 /// Addition for convertible unit_t types with a decibel_scale
2903 template<class UnitTypeLhs, class UnitTypeRhs,
2904 std::enable_if_t<traits::has_decibel_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
2905 constexpr inline auto operator+(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept -> unit_t<compound_unit<squared<typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type>>, typename units::traits::unit_t_traits<UnitTypeLhs>::underlying_type, decibel_scale>
2906 {
2907 using LhsUnits = typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type;
2908 using RhsUnits = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2909 using underlying_type = typename units::traits::unit_t_traits<UnitTypeLhs>::underlying_type;
2910
2911 return unit_t<compound_unit<squared<LhsUnits>>, underlying_type, decibel_scale>
2912 (lhs.template toLinearized<underlying_type>() * convert<RhsUnits, LhsUnits>(rhs.template toLinearized<underlying_type>()), std::true_type());
2913 }
2914
2915 /// Addition between unit_t types with a decibel_scale and dimensionless dB units
2916 template<class UnitTypeLhs, std::enable_if_t<traits::has_decibel_scale<UnitTypeLhs>::value && !traits::is_dimensionless_unit<UnitTypeLhs>::value, int> = 0>
2917 constexpr inline UnitTypeLhs operator+(const UnitTypeLhs& lhs, const dimensionless::dB_t& rhs) noexcept
2918 {
2919 using underlying_type = typename units::traits::unit_t_traits<UnitTypeLhs>::underlying_type;
2920 return UnitTypeLhs(lhs.template toLinearized<underlying_type>() * rhs.template toLinearized<underlying_type>(), std::true_type());
2921 }
2922
2923 /// Addition between unit_t types with a decibel_scale and dimensionless dB units
2924 template<class UnitTypeRhs, std::enable_if_t<traits::has_decibel_scale<UnitTypeRhs>::value && !traits::is_dimensionless_unit<UnitTypeRhs>::value, int> = 0>
2925 constexpr inline UnitTypeRhs operator+(const dimensionless::dB_t& lhs, const UnitTypeRhs& rhs) noexcept
2926 {
2927 using underlying_type = typename units::traits::unit_t_traits<UnitTypeRhs>::underlying_type;
2928 return UnitTypeRhs(lhs.template toLinearized<underlying_type>() * rhs.template toLinearized<underlying_type>(), std::true_type());
2929 }
2930
2931 /// Subtraction for convertible unit_t types with a decibel_scale
2932 template<class UnitTypeLhs, class UnitTypeRhs, std::enable_if_t<traits::has_decibel_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
2933 constexpr inline auto operator-(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs) noexcept -> unit_t<compound_unit<typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type, inverse<typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type>>, typename units::traits::unit_t_traits<UnitTypeLhs>::underlying_type, decibel_scale>
2934 {
2935 using LhsUnits = typename units::traits::unit_t_traits<UnitTypeLhs>::unit_type;
2936 using RhsUnits = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2937 using underlying_type = typename units::traits::unit_t_traits<UnitTypeLhs>::underlying_type;
2938
2940 (lhs.template toLinearized<underlying_type>() / convert<RhsUnits, LhsUnits>(rhs.template toLinearized<underlying_type>()), std::true_type());
2941 }
2942
2943 /// Subtraction between unit_t types with a decibel_scale and dimensionless dB units
2944 template<class UnitTypeLhs, std::enable_if_t<traits::has_decibel_scale<UnitTypeLhs>::value && !traits::is_dimensionless_unit<UnitTypeLhs>::value, int> = 0>
2945 constexpr inline UnitTypeLhs operator-(const UnitTypeLhs& lhs, const dimensionless::dB_t& rhs) noexcept
2946 {
2947 using underlying_type = typename units::traits::unit_t_traits<UnitTypeLhs>::underlying_type;
2948 return UnitTypeLhs(lhs.template toLinearized<underlying_type>() / rhs.template toLinearized<underlying_type>(), std::true_type());
2949 }
2950
2951 /// Subtraction between unit_t types with a decibel_scale and dimensionless dB units
2952 template<class UnitTypeRhs, std::enable_if_t<traits::has_decibel_scale<UnitTypeRhs>::value && !traits::is_dimensionless_unit<UnitTypeRhs>::value, int> = 0>
2953 constexpr inline auto operator-(const dimensionless::dB_t& lhs, const UnitTypeRhs& rhs) noexcept -> unit_t<inverse<typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type>, typename units::traits::unit_t_traits<UnitTypeRhs>::underlying_type, decibel_scale>
2954 {
2955 using RhsUnits = typename units::traits::unit_t_traits<UnitTypeRhs>::unit_type;
2956 using underlying_type = typename units::traits::unit_t_traits<RhsUnits>::underlying_type;
2957
2958 return unit_t<inverse<RhsUnits>, underlying_type, decibel_scale>
2959 (lhs.template toLinearized<underlying_type>() / rhs.template toLinearized<underlying_type>(), std::true_type());
2960 }
2961
2962 //----------------------------------
2963 // UNIT RATIO CLASS
2964 //----------------------------------
2965
2966 /** @cond */ // DOXYGEN IGNORE
2967 namespace detail
2968 {
2969 template<class Units>
2970 struct _unit_value_t {};
2971 }
2972 /** @endcond */ // END DOXYGEN IGNORE
2973
2974 namespace traits
2975 {
2976#ifdef FOR_DOXYGEN_PURPOSES_ONLY
2977 /**
2978 * @ingroup TypeTraits
2979 * @brief Trait for accessing the publicly defined types of `units::unit_value_t_traits`
2980 * @details The units library determines certain properties of the `unit_value_t` types passed to
2981 * them and what they represent by using the members of the corresponding `unit_value_t_traits`
2982 * instantiation.
2983 */
2984 template<typename T>
2985 struct unit_value_t_traits
2986 {
2987 typedef typename T::unit_type unit_type; ///< Dimension represented by the `unit_value_t`.
2988 typedef typename T::ratio ratio; ///< Quantity represented by the `unit_value_t`, expressed as arational number.
2989 };
2990#endif
2991
2992 /** @cond */ // DOXYGEN IGNORE
2993 /**
2994 * @brief unit_value_t_traits specialization for things which are not unit_t
2995 * @details
2996 */
2997 template<typename T, typename = void>
2998 struct unit_value_t_traits
2999 {
3000 typedef void unit_type;
3001 typedef void ratio;
3002 };
3003
3004 /**
3005 * @ingroup TypeTraits
3006 * @brief Trait for accessing the publicly defined types of `units::unit_value_t_traits`
3007 * @details
3008 */
3009 template<typename T>
3010 struct unit_value_t_traits <T, typename void_t<
3011 typename T::unit_type,
3012 typename T::ratio>::type>
3013 {
3014 typedef typename T::unit_type unit_type;
3015 typedef typename T::ratio ratio;
3016 };
3017 /** @endcond */ // END DOXYGEN IGNORE
3018 }
3019
3020 //------------------------------------------------------------------------------
3021 // COMPILE-TIME UNIT VALUES AND ARITHMETIC
3022 //------------------------------------------------------------------------------
3023
3024 /**
3025 * @ingroup UnitContainers
3026 * @brief Stores a rational unit value as a compile-time constant
3027 * @details unit_value_t is useful for performing compile-time arithmetic on known
3028 * unit quantities.
3029 * @tparam Units units represented by the `unit_value_t`
3030 * @tparam Num numerator of the represented value.
3031 * @tparam Denom denominator of the represented value.
3032 * @sa unit_value_t_traits to access information about the properties of the class,
3033 * such as it's unit type and rational value.
3034 * @note This is intentionally identical in concept to a `std::ratio`.
3035 *
3036 */
3037 template<typename Units, std::uintmax_t Num, std::uintmax_t Denom = 1>
3038 struct unit_value_t : units::detail::_unit_value_t<Units>
3039 {
3040 typedef Units unit_type;
3041 typedef std::ratio<Num, Denom> ratio;
3042
3043 static_assert(traits::is_unit<Units>::value, "Template parameter `Units` must be a unit type.");
3044 static constexpr const unit_t<Units> value() { return unit_t<Units>((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den); }
3045 };
3046
3047 namespace traits
3048 {
3049 /**
3050 * @ingroup TypeTraits
3051 * @brief Trait which tests whether a type is a unit_value_t representing the given unit type.
3052 * @details e.g. `is_unit_value_t<meters, myType>::value` would test that `myType` is a
3053 * `unit_value_t<meters>`.
3054 * @tparam Units units that the `unit_value_t` is supposed to have.
3055 * @tparam T type to test.
3056 */
3057 template<typename T, typename Units = typename traits::unit_value_t_traits<T>::unit_type>
3058 struct is_unit_value_t : std::integral_constant<bool,
3059 std::is_base_of<units::detail::_unit_value_t<Units>, T>::value>
3060 {};
3061 template<typename T, typename Units = typename traits::unit_value_t_traits<T>::unit_type>
3063
3064 /**
3065 * @ingroup TypeTraits
3066 * @brief Trait which tests whether type T is a unit_value_t with a unit type in the given category.
3067 * @details e.g. `is_unit_value_t_category<units::category::length, unit_value_t<feet>>::value` would be true
3068 */
3069 template<typename Category, typename T>
3070 struct is_unit_value_t_category : std::integral_constant<bool,
3071 std::is_same<units::traits::base_unit_of<typename traits::unit_value_t_traits<T>::unit_type>, Category>::value>
3072 {
3073 static_assert(is_base_unit<Category>::value, "Template parameter `Category` must be a `base_unit` type.");
3074 };
3075 template<typename Category, typename T>
3077 }
3078
3079 /** @cond */ // DOXYGEN IGNORE
3080 namespace detail
3081 {
3082 // base class for common arithmetic
3083 template<class U1, class U2>
3084 struct unit_value_arithmetic
3085 {
3086 static_assert(traits::is_unit_value_t<U1>::value, "Template parameter `U1` must be a `unit_value_t` type.");
3087 static_assert(traits::is_unit_value_t<U2>::value, "Template parameter `U2` must be a `unit_value_t` type.");
3088
3089 using _UNIT1 = typename traits::unit_value_t_traits<U1>::unit_type;
3090 using _UNIT2 = typename traits::unit_value_t_traits<U2>::unit_type;
3091 using _CONV1 = typename units::traits::unit_traits<_UNIT1>::conversion_ratio;
3092 using _CONV2 = typename units::traits::unit_traits<_UNIT2>::conversion_ratio;
3093 using _RATIO1 = typename traits::unit_value_t_traits<U1>::ratio;
3094 using _RATIO2 = typename traits::unit_value_t_traits<U2>::ratio;
3095 using _RATIO2CONV = typename std::ratio_divide<std::ratio_multiply<_RATIO2, _CONV2>, _CONV1>;
3096 using _PI_EXP = std::ratio_subtract<typename units::traits::unit_traits<_UNIT2>::pi_exponent_ratio, typename units::traits::unit_traits<_UNIT1>::pi_exponent_ratio>;
3097 };
3098 }
3099 /** @endcond */ // END DOXYGEN IGNORE
3100
3101 /**
3102 * @ingroup CompileTimeUnitManipulators
3103 * @brief adds two unit_value_t types at compile-time
3104 * @details The resulting unit will the the `unit_type` of `U1`
3105 * @tparam U1 left-hand `unit_value_t`
3106 * @tparam U2 right-hand `unit_value_t`
3107 * @sa unit_value_t_traits to access information about the properties of the class,
3108 * such as it's unit type and rational value.
3109 * @note very similar in concept to `std::ratio_add`
3110 */
3111 template<class U1, class U2>
3112 struct unit_value_add : units::detail::unit_value_arithmetic<U1, U2>, units::detail::_unit_value_t<typename traits::unit_value_t_traits<U1>::unit_type>
3113 {
3114 /** @cond */ // DOXYGEN IGNORE
3115 using Base = units::detail::unit_value_arithmetic<U1, U2>;
3116 typedef typename Base::_UNIT1 unit_type;
3117 using ratio = std::ratio_add<typename Base::_RATIO1, typename Base::_RATIO2CONV>;
3118
3119 static_assert(traits::is_convertible_unit<typename Base::_UNIT1, typename Base::_UNIT2>::value, "Unit types are not compatible.");
3120 /** @endcond */ // END DOXYGEN IGNORE
3121
3122 /**
3123 * @brief Value of sum
3124 * @details Returns the calculated value of the sum of `U1` and `U2`, in the same
3125 * units as `U1`.
3126 * @returns Value of the sum in the appropriate units.
3127 */
3128 static constexpr const unit_t<unit_type> value() noexcept
3129 {
3130 using UsePi = std::integral_constant<bool, Base::_PI_EXP::num != 0>;
3131 return value(UsePi());
3132 }
3133
3134 /** @cond */ // DOXYGEN IGNORE
3135 // value if PI isn't involved
3136 static constexpr const unit_t<unit_type> value(std::false_type) noexcept
3137 {
3138 return unit_t<unit_type>((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den);
3139 }
3140
3141 // value if PI *is* involved
3142 static constexpr const unit_t<unit_type> value(std::true_type) noexcept
3143 {
3144 return unit_t<unit_type>(((UNIT_LIB_DEFAULT_TYPE)Base::_RATIO1::num / Base::_RATIO1::den) +
3145 ((UNIT_LIB_DEFAULT_TYPE)Base::_RATIO2CONV::num / Base::_RATIO2CONV::den) * std::pow(units::constants::detail::PI_VAL, ((UNIT_LIB_DEFAULT_TYPE)Base::_PI_EXP::num / Base::_PI_EXP::den)));
3146 }
3147 /** @endcond */ // END DOXYGEN IGNORE
3148 };
3149
3150 /**
3151 * @ingroup CompileTimeUnitManipulators
3152 * @brief subtracts two unit_value_t types at compile-time
3153 * @details The resulting unit will the the `unit_type` of `U1`
3154 * @tparam U1 left-hand `unit_value_t`
3155 * @tparam U2 right-hand `unit_value_t`
3156 * @sa unit_value_t_traits to access information about the properties of the class,
3157 * such as it's unit type and rational value.
3158 * @note very similar in concept to `std::ratio_subtract`
3159 */
3160 template<class U1, class U2>
3161 struct unit_value_subtract : units::detail::unit_value_arithmetic<U1, U2>, units::detail::_unit_value_t<typename traits::unit_value_t_traits<U1>::unit_type>
3162 {
3163 /** @cond */ // DOXYGEN IGNORE
3164 using Base = units::detail::unit_value_arithmetic<U1, U2>;
3165
3166 typedef typename Base::_UNIT1 unit_type;
3167 using ratio = std::ratio_subtract<typename Base::_RATIO1, typename Base::_RATIO2CONV>;
3168
3169 static_assert(traits::is_convertible_unit<typename Base::_UNIT1, typename Base::_UNIT2>::value, "Unit types are not compatible.");
3170 /** @endcond */ // END DOXYGEN IGNORE
3171
3172 /**
3173 * @brief Value of difference
3174 * @details Returns the calculated value of the difference of `U1` and `U2`, in the same
3175 * units as `U1`.
3176 * @returns Value of the difference in the appropriate units.
3177 */
3178 static constexpr const unit_t<unit_type> value() noexcept
3179 {
3180 using UsePi = std::integral_constant<bool, Base::_PI_EXP::num != 0>;
3181 return value(UsePi());
3182 }
3183
3184 /** @cond */ // DOXYGEN IGNORE
3185 // value if PI isn't involved
3186 static constexpr const unit_t<unit_type> value(std::false_type) noexcept
3187 {
3188 return unit_t<unit_type>((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den);
3189 }
3190
3191 // value if PI *is* involved
3192 static constexpr const unit_t<unit_type> value(std::true_type) noexcept
3193 {
3194 return unit_t<unit_type>(((UNIT_LIB_DEFAULT_TYPE)Base::_RATIO1::num / Base::_RATIO1::den) - ((UNIT_LIB_DEFAULT_TYPE)Base::_RATIO2CONV::num / Base::_RATIO2CONV::den)
3195 * std::pow(units::constants::detail::PI_VAL, ((UNIT_LIB_DEFAULT_TYPE)Base::_PI_EXP::num / Base::_PI_EXP::den)));
3196 }
3197 /** @endcond */ // END DOXYGEN IGNORE };
3198 };
3199
3200 /**
3201 * @ingroup CompileTimeUnitManipulators
3202 * @brief multiplies two unit_value_t types at compile-time
3203 * @details The resulting unit will the the `unit_type` of `U1 * U2`
3204 * @tparam U1 left-hand `unit_value_t`
3205 * @tparam U2 right-hand `unit_value_t`
3206 * @sa unit_value_t_traits to access information about the properties of the class,
3207 * such as it's unit type and rational value.
3208 * @note very similar in concept to `std::ratio_multiply`
3209 */
3210 template<class U1, class U2>
3211 struct unit_value_multiply : units::detail::unit_value_arithmetic<U1, U2>,
3212 units::detail::_unit_value_t<typename std::conditional<traits::is_convertible_unit<typename traits::unit_value_t_traits<U1>::unit_type,
3213 typename traits::unit_value_t_traits<U2>::unit_type>::value, compound_unit<squared<typename traits::unit_value_t_traits<U1>::unit_type>>,
3214 compound_unit<typename traits::unit_value_t_traits<U1>::unit_type, typename traits::unit_value_t_traits<U2>::unit_type>>::type>
3215 {
3216 /** @cond */ // DOXYGEN IGNORE
3217 using Base = units::detail::unit_value_arithmetic<U1, U2>;
3218
3219 using unit_type = std::conditional_t<traits::is_convertible_unit<typename Base::_UNIT1, typename Base::_UNIT2>::value, compound_unit<squared<typename Base::_UNIT1>>, compound_unit<typename Base::_UNIT1, typename Base::_UNIT2>>;
3220 using ratio = std::conditional_t<traits::is_convertible_unit<typename Base::_UNIT1, typename Base::_UNIT2>::value, std::ratio_multiply<typename Base::_RATIO1, typename Base::_RATIO2CONV>, std::ratio_multiply<typename Base::_RATIO1, typename Base::_RATIO2>>;
3221 /** @endcond */ // END DOXYGEN IGNORE
3222
3223 /**
3224 * @brief Value of product
3225 * @details Returns the calculated value of the product of `U1` and `U2`, in units
3226 * of `U1 x U2`.
3227 * @returns Value of the product in the appropriate units.
3228 */
3229 static constexpr const unit_t<unit_type> value() noexcept
3230 {
3231 using UsePi = std::integral_constant<bool, Base::_PI_EXP::num != 0>;
3232 return value(UsePi());
3233 }
3234
3235 /** @cond */ // DOXYGEN IGNORE
3236 // value if PI isn't involved
3237 static constexpr const unit_t<unit_type> value(std::false_type) noexcept
3238 {
3239 return unit_t<unit_type>((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den);
3240 }
3241
3242 // value if PI *is* involved
3243 static constexpr const unit_t<unit_type> value(std::true_type) noexcept
3244 {
3245 return unit_t<unit_type>(((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den) * std::pow(units::constants::detail::PI_VAL, ((UNIT_LIB_DEFAULT_TYPE)Base::_PI_EXP::num / Base::_PI_EXP::den)));
3246 }
3247 /** @endcond */ // END DOXYGEN IGNORE
3248 };
3249
3250 /**
3251 * @ingroup CompileTimeUnitManipulators
3252 * @brief divides two unit_value_t types at compile-time
3253 * @details The resulting unit will the the `unit_type` of `U1`
3254 * @tparam U1 left-hand `unit_value_t`
3255 * @tparam U2 right-hand `unit_value_t`
3256 * @sa unit_value_t_traits to access information about the properties of the class,
3257 * such as it's unit type and rational value.
3258 * @note very similar in concept to `std::ratio_divide`
3259 */
3260 template<class U1, class U2>
3261 struct unit_value_divide : units::detail::unit_value_arithmetic<U1, U2>,
3262 units::detail::_unit_value_t<typename std::conditional<traits::is_convertible_unit<typename traits::unit_value_t_traits<U1>::unit_type,
3263 typename traits::unit_value_t_traits<U2>::unit_type>::value, dimensionless::scalar, compound_unit<typename traits::unit_value_t_traits<U1>::unit_type,
3264 inverse<typename traits::unit_value_t_traits<U2>::unit_type>>>::type>
3265 {
3266 /** @cond */ // DOXYGEN IGNORE
3267 using Base = units::detail::unit_value_arithmetic<U1, U2>;
3268
3269 using unit_type = std::conditional_t<traits::is_convertible_unit<typename Base::_UNIT1, typename Base::_UNIT2>::value, dimensionless::scalar, compound_unit<typename Base::_UNIT1, inverse<typename Base::_UNIT2>>>;
3270 using ratio = std::conditional_t<traits::is_convertible_unit<typename Base::_UNIT1, typename Base::_UNIT2>::value, std::ratio_divide<typename Base::_RATIO1, typename Base::_RATIO2CONV>, std::ratio_divide<typename Base::_RATIO1, typename Base::_RATIO2>>;
3271 /** @endcond */ // END DOXYGEN IGNORE
3272
3273 /**
3274 * @brief Value of quotient
3275 * @details Returns the calculated value of the quotient of `U1` and `U2`, in units
3276 * of `U1 x U2`.
3277 * @returns Value of the quotient in the appropriate units.
3278 */
3279 static constexpr const unit_t<unit_type> value() noexcept
3280 {
3281 using UsePi = std::integral_constant<bool, Base::_PI_EXP::num != 0>;
3282 return value(UsePi());
3283 }
3284
3285 /** @cond */ // DOXYGEN IGNORE
3286 // value if PI isn't involved
3287 static constexpr const unit_t<unit_type> value(std::false_type) noexcept
3288 {
3289 return unit_t<unit_type>((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den);
3290 }
3291
3292 // value if PI *is* involved
3293 static constexpr const unit_t<unit_type> value(std::true_type) noexcept
3294 {
3295 return unit_t<unit_type>(((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den) * std::pow(units::constants::detail::PI_VAL, ((UNIT_LIB_DEFAULT_TYPE)Base::_PI_EXP::num / Base::_PI_EXP::den)));
3296 }
3297 /** @endcond */ // END DOXYGEN IGNORE
3298 };
3299
3300 /**
3301 * @ingroup CompileTimeUnitManipulators
3302 * @brief raises unit_value_to a power at compile-time
3303 * @details The resulting unit will the `unit_type` of `U1` squared
3304 * @tparam U1 `unit_value_t` to take the exponentiation of.
3305 * @sa unit_value_t_traits to access information about the properties of the class,
3306 * such as it's unit type and rational value.
3307 * @note very similar in concept to `units::math::pow`
3308 */
3309 template<class U1, int power>
3310 struct unit_value_power : units::detail::unit_value_arithmetic<U1, U1>, units::detail::_unit_value_t<typename units::detail::power_of_unit<power, typename traits::unit_value_t_traits<U1>::unit_type>::type>
3311 {
3312 /** @cond */ // DOXYGEN IGNORE
3313 using Base = units::detail::unit_value_arithmetic<U1, U1>;
3314
3317 using pi_exponent = std::ratio_multiply<std::ratio<power>, typename Base::_UNIT1::pi_exponent_ratio>;
3318 /** @endcond */ // END DOXYGEN IGNORE
3319
3320 /**
3321 * @brief Value of exponentiation
3322 * @details Returns the calculated value of the exponentiation of `U1`, in units
3323 * of `U1^power`.
3324 * @returns Value of the exponentiation in the appropriate units.
3325 */
3326 static constexpr const unit_t<unit_type> value() noexcept
3327 {
3328 using UsePi = std::integral_constant<bool, Base::_PI_EXP::num != 0>;
3329 return value(UsePi());
3330 }
3331
3332 /** @cond */ // DOXYGEN IGNORE
3333 // value if PI isn't involved
3334 static constexpr const unit_t<unit_type> value(std::false_type) noexcept
3335 {
3336 return unit_t<unit_type>((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den);
3337 }
3338
3339 // value if PI *is* involved
3340 static constexpr const unit_t<unit_type> value(std::true_type) noexcept
3341 {
3342 return unit_t<unit_type>(((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den) * std::pow(units::constants::detail::PI_VAL, ((UNIT_LIB_DEFAULT_TYPE)pi_exponent::num / pi_exponent::den)));
3343 }
3344 /** @endcond */ // END DOXYGEN IGNORE };
3345 };
3346
3347 /**
3348 * @ingroup CompileTimeUnitManipulators
3349 * @brief calculates square root of unit_value_t at compile-time
3350 * @details The resulting unit will the square root `unit_type` of `U1`
3351 * @tparam U1 `unit_value_t` to take the square root of.
3352 * @sa unit_value_t_traits to access information about the properties of the class,
3353 * such as it's unit type and rational value.
3354 * @note very similar in concept to `units::ratio_sqrt`
3355 */
3356 template<class U1, std::intmax_t Eps = 10000000000>
3357 struct unit_value_sqrt : units::detail::unit_value_arithmetic<U1, U1>, units::detail::_unit_value_t<square_root<typename traits::unit_value_t_traits<U1>::unit_type, Eps>>
3358 {
3359 /** @cond */ // DOXYGEN IGNORE
3360 using Base = units::detail::unit_value_arithmetic<U1, U1>;
3361
3365 /** @endcond */ // END DOXYGEN IGNORE
3366
3367 /**
3368 * @brief Value of square root
3369 * @details Returns the calculated value of the square root of `U1`, in units
3370 * of `U1^1/2`.
3371 * @returns Value of the square root in the appropriate units.
3372 */
3373 static constexpr const unit_t<unit_type> value() noexcept
3374 {
3375 using UsePi = std::integral_constant<bool, Base::_PI_EXP::num != 0>;
3376 return value(UsePi());
3377 }
3378
3379 /** @cond */ // DOXYGEN IGNORE
3380 // value if PI isn't involved
3381 static constexpr const unit_t<unit_type> value(std::false_type) noexcept
3382 {
3383 return unit_t<unit_type>((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den);
3384 }
3385
3386 // value if PI *is* involved
3387 static constexpr const unit_t<unit_type> value(std::true_type) noexcept
3388 {
3389 return unit_t<unit_type>(((UNIT_LIB_DEFAULT_TYPE)ratio::num / ratio::den) * std::pow(units::constants::detail::PI_VAL, ((UNIT_LIB_DEFAULT_TYPE)pi_exponent::num / pi_exponent::den)));
3390 }
3391 /** @endcond */ // END DOXYGEN IGNORE
3392 };
3393
3394 //----------------------------------
3395 // UNIT-ENABLED CMATH FUNCTIONS
3396 //----------------------------------
3397
3398 /**
3399 * @brief namespace for unit-enabled versions of the `<cmath>` library
3400 * @details Includes trigonometric functions, exponential/log functions, rounding functions, etc.
3401 * @sa See `unit_t` for more information on unit type containers.
3402 */
3403 namespace math
3404 {
3405
3406 //----------------------------------
3407 // MIN/MAX FUNCTIONS
3408 //----------------------------------
3409 // XXX: min/max are defined here instead of math.h to avoid a conflict with
3410 // the "_min" user-defined literal in time.h.
3411
3412 template<class UnitTypeLhs, class UnitTypeRhs>
3413 constexpr UnitTypeLhs (min)(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs)
3414 {
3415 static_assert(traits::is_convertible_unit_t<UnitTypeLhs, UnitTypeRhs>::value, "Unit types are not compatible.");
3416 UnitTypeLhs r(rhs);
3417 return (lhs < r ? lhs : r);
3418 }
3419
3420 template<class UnitTypeLhs, class UnitTypeRhs>
3421 constexpr UnitTypeLhs (max)(const UnitTypeLhs& lhs, const UnitTypeRhs& rhs)
3422 {
3423 static_assert(traits::is_convertible_unit_t<UnitTypeLhs, UnitTypeRhs>::value, "Unit types are not compatible.");
3424 UnitTypeLhs r(rhs);
3425 return (lhs > r ? lhs : r);
3426 }
3427 }
3428}
3429
3430#ifdef _MSC_VER
3431# if _MSC_VER <= 1800
3432# pragma warning(pop)
3433# undef constexpr
3434# pragma pop_macro("constexpr")
3435# undef noexcept
3436# pragma pop_macro("noexcept")
3437# undef _ALLOW_KEYWORD_MACROS
3438# endif // _MSC_VER < 1800
3439# pragma pop_macro("pascal")
3440#endif // _MSC_VER
3441
3442#if defined(UNIT_HAS_LITERAL_SUPPORT)
3444using namespace units::literals;
3445#endif // UNIT_HAS_LITERAL_SUPPORT
3446
3447#if __has_include(<fmt/format.h>) && !defined(UNIT_LIB_DISABLE_FMT)
3448#include "units/formatter.h"
3449#endif
Container for values which represent quantities of a given unit.
Definition: base.h:1929
constexpr bool operator<(const unit_t< UnitsRhs, Ty, NlsRhs > &rhs) const noexcept
less-than
Definition: base.h:2031
constexpr bool operator<=(const unit_t< UnitsRhs, Ty, NlsRhs > &rhs) const noexcept
less-than or equal
Definition: base.h:2043
constexpr unit_t< U > convert() const noexcept
conversion
Definition: base.h:2146
unit_t & operator=(const Ty &rhs) noexcept
assignment
Definition: base.h:2018
constexpr unit_t(const std::chrono::duration< Rep, Period > &value) noexcept
chrono constructor
Definition: base.h:1982
constexpr underlying_type value() const noexcept
unit value
Definition: base.h:2110
constexpr unit_t(const Ty value) noexcept
constructor
Definition: base.h:1971
constexpr unit_t(const unit_t< UnitsRhs, Ty, NlsRhs > &rhs) noexcept
copy constructor (converting)
Definition: base.h:1994
constexpr const char * name() const noexcept
returns the unit name
Definition: base.h:2186
constexpr Ty toLinearized() const noexcept
linearized unit value
Definition: base.h:2131
constexpr Ty to() const noexcept
unit value
Definition: base.h:2120
constexpr bool operator!=(const unit_t< UnitsRhs, Ty, NlsRhs > &rhs) const noexcept
inequality
Definition: base.h:2101
Units unit_type
Type of unit the unit_t represents (e.g. meters)
Definition: base.h:1943
constexpr bool operator>(const unit_t< UnitsRhs, Ty, NlsRhs > &rhs) const noexcept
greater-than
Definition: base.h:2055
T value_type
Synonym for underlying type. May be removed in future versions. Prefer underlying_type.
Definition: base.h:1942
constexpr bool operator==(const unit_t< UnitsRhs, Ty, NlsRhs > &rhs) const noexcept
equality
Definition: base.h:2080
constexpr unit_t(const T value, const Args &... args) noexcept
constructor
Definition: base.h:1960
constexpr const char * abbreviation() const noexcept
returns the unit abbreviation
Definition: base.h:2194
NonLinearScale< T > non_linear_scale_type
Type of the non-linear scale of the unit_t (e.g. linear_scale)
Definition: base.h:1940
NonLinearScale< T > nls
Definition: base.h:1935
constexpr bool operator>=(const unit_t< UnitsRhs, Ty, NlsRhs > &rhs) const noexcept
greater-than or equal
Definition: base.h:2067
constexpr unit_t()=default
default constructor.
unit_t & operator=(const unit_t< UnitsRhs, Ty, NlsRhs > &rhs) noexcept
assignment
Definition: base.h:2006
T underlying_type
Type of the underlying storage of the unit_t (e.g. double)
Definition: base.h:1941
constexpr T unit_cast(const Units &value) noexcept
Casts a unit container to an arithmetic type.
Definition: base.h:2395
static constexpr T convert(const T &value) noexcept
converts a value from one type to another.
Definition: base.h:1651
typename units::detail::Sqrt< Ratio, std::ratio< 1, Eps > >::type ratio_sqrt
Calculate square root of a ratio at compile-time.
Definition: base.h:1359
constexpr UnitType make_unit(const T value) noexcept
Constructs a unit container from an arithmetic type.
Definition: base.h:2220
typename units::detail::prefix< std::peta, U >::type peta
Represents the type of class U with the metric 'peta' prefix appended.
Definition: base.h:1494
typename units::detail::prefix< std::ratio< 1099511627776 >, U >::type tebi
Represents the type of class U with the binary 'tebi' prefix appended.
Definition: base.h:1507
typename units::detail::prefix< std::milli, U >::type milli
Represents the type of class U with the metric 'milli' prefix appended.
Definition: base.h:1485
typename units::detail::inverse_impl< U >::type inverse
represents the inverse unit type of class U.
Definition: base.h:1137
typename units::detail::prefix< std::micro, U >::type micro
Represents the type of class U with the metric 'micro' prefix appended.
Definition: base.h:1484
typename units::detail::prefix< std::ratio< 1048576 >, U >::type mebi
Represents the type of class U with the binary 'mibi' prefix appended.
Definition: base.h:1505
typename units::detail::prefix< std::ratio< 1152921504606846976 >, U >::type exbi
Represents the type of class U with the binary 'exbi' prefix appended.
Definition: base.h:1509
typename units::detail::prefix< std::giga, U >::type giga
Represents the type of class U with the metric 'giga' prefix appended.
Definition: base.h:1492
typename units::detail::squared_impl< U >::type squared
represents the unit type of class U squared
Definition: base.h:1168
typename units::detail::prefix< std::deca, U >::type deca
Represents the type of class U with the metric 'deca' prefix appended.
Definition: base.h:1488
typename units::detail::prefix< std::deci, U >::type deci
Represents the type of class U with the metric 'deci' prefix appended.
Definition: base.h:1487
typename units::detail::cubed_impl< U >::type cubed
represents the type of class U cubed.
Definition: base.h:1198
typename units::detail::prefix< std::femto, U >::type femto
Represents the type of class U with the metric 'femto' prefix appended.
Definition: base.h:1481
typename units::detail::prefix< std::pico, U >::type pico
Represents the type of class U with the metric 'pico' prefix appended.
Definition: base.h:1482
typename units::detail::prefix< std::tera, U >::type tera
Represents the type of class U with the metric 'tera' prefix appended.
Definition: base.h:1493
typename units::detail::prefix< std::hecto, U >::type hecto
Represents the type of class U with the metric 'hecto' prefix appended.
Definition: base.h:1489
typename units::detail::prefix< std::atto, U >::type atto
Represents the type of class U with the metric 'atto' prefix appended.
Definition: base.h:1480
typename units::detail::prefix< std::ratio< 1073741824 >, U >::type gibi
Represents the type of class U with the binary 'gibi' prefix appended.
Definition: base.h:1506
typename units::detail::prefix< std::exa, U >::type exa
Represents the type of class U with the metric 'exa' prefix appended.
Definition: base.h:1495
typename units::detail::sqrt_impl< U, Eps >::type square_root
represents the square root of type class U.
Definition: base.h:1404
typename units::detail::prefix< std::ratio< 1125899906842624 >, U >::type pebi
Represents the type of class U with the binary 'pebi' prefix appended.
Definition: base.h:1508
typename units::detail::prefix< std::ratio< 1024 >, U >::type kibi
Represents the type of class U with the binary 'kibi' prefix appended.
Definition: base.h:1504
typename units::detail::prefix< std::centi, U >::type centi
Represents the type of class U with the metric 'centi' prefix appended.
Definition: base.h:1486
typename units::detail::prefix< std::nano, U >::type nano
Represents the type of class U with the metric 'nano' prefix appended.
Definition: base.h:1483
typename units::detail::prefix< std::mega, U >::type mega
Represents the type of class U with the metric 'mega' prefix appended.
Definition: base.h:1491
typename units::detail::prefix< std::kilo, U >::type kilo
Represents the type of class U with the metric 'kilo' prefix appended.
Definition: base.h:1490
constexpr UnitType abs(const UnitType x) noexcept
Compute absolute value.
Definition: math.h:726
constexpr dimensionless::scalar_t log10(const ScalarUnit x) noexcept
Compute common logarithm.
Definition: math.h:367
typename units::detail::compound_impl< U, Us... >::type compound_unit
Represents a unit type made up from other units.
Definition: base.h:1437
detail namespace with internal helper functions
Definition: chrono.h:321
@ value
the parser finished reading a JSON value
constexpr auto count() -> size_t
Definition: base.h:1279
type
Definition: base.h:646
constexpr common_t< T1, T2 > pow(const T1 base, const T2 exp_term) noexcept
Compile-time power function.
Definition: pow.hpp:82
Implement std::hash so that hash_code can be used in STL containers.
Definition: array.h:89
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > time_unit
Represents an SI base unit of time.
Definition: base.h:800
base_unit< detail::meter_ratio< 0 >, std::ratio< 1 > > mass_unit
Represents an SI base unit of mass.
Definition: base.h:799
base_unit< detail::meter_ratio<-3 >, std::ratio< 1 > > density_unit
Represents an SI derived unit of density.
Definition: base.h:837
base_unit< detail::meter_ratio< 2 >, std::ratio< 1 >, std::ratio<-2 >, std::ratio< 0 >, std::ratio<-1 > > magnetic_flux_unit
Represents an SI derived unit of magnetic flux.
Definition: base.h:825
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio<-1 >, std::ratio< 1 > > angular_velocity_unit
Represents an SI derived unit of angular velocity.
Definition: base.h:812
base_unit< detail::meter_ratio< 2 >, std::ratio< 1 >, std::ratio<-3 >, std::ratio< 0 >, std::ratio<-2 > > impedance_unit
Represents an SI derived unit of impedance.
Definition: base.h:823
base_unit< detail::meter_ratio< 1 > > length_unit
Represents an SI base unit of length.
Definition: base.h:798
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > luminous_intensity_unit
Represents an SI base unit of luminous intensity.
Definition: base.h:805
base_unit concentration_unit
Represents a unit of concentration.
Definition: base.h:838
base_unit< detail::meter_ratio< 2 >, std::ratio< 1 >, std::ratio<-2 > > energy_unit
Represents an SI derived unit of energy.
Definition: base.h:819
base_unit< detail::meter_ratio< 3 > > volume_unit
Represents an SI derived unit of volume.
Definition: base.h:836
base_unit< detail::meter_ratio<-2 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 2 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > illuminance_unit
Represents an SI derived unit of illuminance.
Definition: base.h:829
base_unit dimensionless_unit
Represents a quantity with no dimension.
Definition: base.h:794
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > data_unit
Represents a unit of data size.
Definition: base.h:839
base_unit< detail::meter_ratio<-1 >, std::ratio< 1 >, std::ratio<-2 > > pressure_unit
Represents an SI derived unit of pressure.
Definition: base.h:817
base_unit< detail::meter_ratio< 1 >, std::ratio< 0 >, std::ratio<-2 > > acceleration_unit
Represents an SI derived unit of acceleration.
Definition: base.h:813
base_unit scalar_unit
Represents a quantity with no dimension.
Definition: base.h:793
base_unit< detail::meter_ratio< 2 >, std::ratio< 1 >, std::ratio<-3 > > power_unit
Represents an SI derived unit of power.
Definition: base.h:820
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio<-1 > > frequency_unit
Represents an SI derived unit of frequency.
Definition: base.h:810
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > angle_unit
Represents an SI base unit of angle.
Definition: base.h:801
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > current_unit
Represents an SI base unit of current.
Definition: base.h:802
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 1 >, std::ratio< 0 >, std::ratio< 1 > > charge_unit
Represents an SI derived unit of charge.
Definition: base.h:818
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 2 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 > > solid_angle_unit
Represents an SI derived unit of solid angle.
Definition: base.h:809
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > substance_unit
Represents an SI base unit of amount of substance.
Definition: base.h:804
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio<-3 >, std::ratio< 1 > > angular_jerk_unit
Represents an SI derived unit of angular jerk.
Definition: base.h:815
base_unit< detail::meter_ratio< 2 >, std::ratio< 1 >, std::ratio<-3 >, std::ratio< 0 >, std::ratio<-1 > > voltage_unit
Represents an SI derived unit of voltage.
Definition: base.h:821
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio<-1 > > radioactivity_unit
Represents an SI derived unit of radioactivity.
Definition: base.h:830
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 2 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > luminous_flux_unit
Represents an SI derived unit of luminous flux.
Definition: base.h:828
base_unit< detail::meter_ratio< 2 >, std::ratio< 1 >, std::ratio<-2 > > torque_unit
Represents an SI derived unit of torque.
Definition: base.h:834
base_unit< detail::meter_ratio< 2 >, std::ratio< 1 >, std::ratio<-2 >, std::ratio< 0 >, std::ratio<-2 > > inductance_unit
Represents an SI derived unit of inductance.
Definition: base.h:827
base_unit< detail::meter_ratio< 1 >, std::ratio< 0 >, std::ratio<-1 > > velocity_unit
Represents an SI derived unit of velocity.
Definition: base.h:811
base_unit< detail::meter_ratio< 1 >, std::ratio< 1 >, std::ratio<-2 > > force_unit
Represents an SI derived unit of force.
Definition: base.h:816
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio<-2 >, std::ratio< 1 > > angular_acceleration_unit
Represents an SI derived unit of angular acceleration.
Definition: base.h:814
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio<-1 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > data_transfer_rate_unit
Represents a unit of data transfer rate.
Definition: base.h:840
base_unit< detail::meter_ratio<-2 >, std::ratio<-1 >, std::ratio< 4 >, std::ratio< 0 >, std::ratio< 2 > > capacitance_unit
Represents an SI derived unit of capacitance.
Definition: base.h:822
base_unit< detail::meter_ratio<-2 >, std::ratio<-1 >, std::ratio< 3 >, std::ratio< 0 >, std::ratio< 2 > > conductance_unit
Represents an SI derived unit of conductance.
Definition: base.h:824
base_unit< detail::meter_ratio< 0 >, std::ratio< 1 >, std::ratio<-2 >, std::ratio< 0 >, std::ratio<-1 > > magnetic_field_strength_unit
Represents an SI derived unit of magnetic field strength.
Definition: base.h:826
base_unit< detail::meter_ratio< 2 > > area_unit
Represents an SI derived unit of area.
Definition: base.h:835
base_unit< detail::meter_ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 0 >, std::ratio< 1 > > temperature_unit
Represents an SI base unit of temperature.
Definition: base.h:803
static constexpr const unit_t< compound_unit< energy::joules, inverse< temperature::kelvin >, inverse< substance::moles > > > R(8.3144598)
Gas constant.
std::string to_string(const T &t)
Definition: base.h:94
unit_t< scalar, UNIT_LIB_DEFAULT_TYPE, decibel_scale > dB_t
Definition: base.h:2871
unit< std::ratio< 1 >, units::category::dimensionless_unit > dimensionless
Definition: base.h:2514
dB_t dBi_t
Definition: base.h:2872
scalar_t dimensionless_t
Definition: base.h:2517
unit_t< scalar > scalar_t
Definition: base.h:2516
unit< std::ratio< 1 >, units::category::scalar_unit > scalar
Definition: base.h:2513
Definition: base.h:3443
constexpr UnitTypeLhs() min(const UnitTypeLhs &lhs, const UnitTypeRhs &rhs)
Definition: base.h:3413
constexpr UnitTypeLhs() max(const UnitTypeLhs &lhs, const UnitTypeRhs &rhs)
Definition: base.h:3421
constexpr auto cpow(const UnitType &value) noexcept -> unit_t< typename units::detail::power_of_unit< power, typename units::traits::unit_t_traits< UnitType >::unit_type >::type, typename units::traits::unit_t_traits< UnitType >::underlying_type, linear_scale >
computes the value of value raised to the power as a constexpr
Definition: base.h:2824
constexpr auto pow(const UnitType &value) noexcept -> unit_t< typename units::detail::power_of_unit< power, typename units::traits::unit_t_traits< UnitType >::unit_type >::type, typename units::traits::unit_t_traits< UnitType >::underlying_type, linear_scale >
computes the value of value raised to the power
Definition: base.h:2809
constexpr bool has_decibel_scale_v
Definition: base.h:2442
constexpr bool is_convertible_unit_v
Definition: base.h:1534
constexpr bool has_linear_scale_v
Definition: base.h:2420
constexpr bool is_unit_value_t_category_v
Definition: base.h:3076
constexpr bool is_same_scale_v
Definition: base.h:2466
constexpr bool is_unit_v
Definition: base.h:723
constexpr bool is_unit_t_v
Definition: base.h:1869
typename units::detail::base_unit_of_impl< U >::type base_unit_of
Trait which returns the base_unit type that a unit is originally derived from.
Definition: base.h:935
constexpr bool is_ratio_v
Definition: base.h:595
constexpr bool is_unit_value_t_v
Definition: base.h:3062
Unit Conversion Library namespace.
Definition: temperature.h:31
unit_t< Units, T, NonLinearScale > & operator*=(unit_t< Units, T, NonLinearScale > &lhs, const RhsType &rhs) noexcept
Definition: base.h:2306
unit_t< Units, T, NonLinearScale > & operator/=(unit_t< Units, T, NonLinearScale > &lhs, const RhsType &rhs) noexcept
Definition: base.h:2316
constexpr bool operator!=(const UNIT_LIB_DEFAULT_TYPE lhs, const Units &rhs) noexcept
Definition: base.h:2719
unit_t< Units, T, NonLinearScale > & operator+=(unit_t< Units, T, NonLinearScale > &lhs, const RhsType &rhs) noexcept
Definition: base.h:2284
constexpr const char * abbreviation(const T &)
constexpr bool operator==(const UNIT_LIB_DEFAULT_TYPE lhs, const Units &rhs) noexcept
Definition: base.h:2705
constexpr dimensionless::scalar_t operator/(const UnitTypeLhs &lhs, const UnitTypeRhs &rhs) noexcept
Division for convertible unit_t types with a linear scale.
Definition: base.h:2647
constexpr const char * name(const T &)
constexpr bool operator<(const UNIT_LIB_DEFAULT_TYPE lhs, const Units &rhs) noexcept
Definition: base.h:2767
unit_t< Units, T, NonLinearScale > & operator++(unit_t< Units, T, NonLinearScale > &u) noexcept
Definition: base.h:2338
unit_t< Units, T, NonLinearScale > & operator-=(unit_t< Units, T, NonLinearScale > &lhs, const RhsType &rhs) noexcept
Definition: base.h:2295
constexpr bool operator<=(const UNIT_LIB_DEFAULT_TYPE lhs, const Units &rhs) noexcept
Definition: base.h:2755
unit_t< Units, T, NonLinearScale > & operator--(unit_t< Units, T, NonLinearScale > &u) noexcept
Definition: base.h:2362
constexpr bool operator>=(const UNIT_LIB_DEFAULT_TYPE lhs, const Units &rhs) noexcept
Definition: base.h:2731
constexpr bool operator>(const UNIT_LIB_DEFAULT_TYPE lhs, const Units &rhs) noexcept
Definition: base.h:2743
constexpr unit_t< Units, T, NonLinearScale > operator-(const unit_t< Units, T, NonLinearScale > &u) noexcept
Definition: base.h:2355
constexpr unit_t< Units, T, NonLinearScale > operator+(const unit_t< Units, T, NonLinearScale > &u) noexcept
Definition: base.h:2331
constexpr auto operator*(const UnitTypeLhs &lhs, const UnitTypeRhs &rhs) noexcept -> unit_t< compound_unit< squared< typename units::traits::unit_t_traits< UnitTypeLhs >::unit_type > > >
Multiplication type for convertible unit_t types with a linear scale.
Definition: base.h:2591
std::enable_if_t<!std::is_reference_v< OStream > &&std::is_base_of_v< raw_ostream, OStream >, OStream && > operator<<(OStream &&OS, const T &Value)
Call the appropriate insertion operator, given an rvalue reference to a raw_ostream object and return...
Definition: raw_ostream.h:398
Class representing SI base unit types.
Definition: base.h:760
Kilogram kilogram_ratio
Definition: base.h:772
Radian radian_ratio
Definition: base.h:774
Kelvin kelvin_ratio
Definition: base.h:776
Ampere ampere_ratio
Definition: base.h:775
Byte byte_ratio
Definition: base.h:779
Candela candela_ratio
Definition: base.h:778
Second second_ratio
Definition: base.h:773
Meter meter_ratio
Definition: base.h:771
Mole mole_ratio
Definition: base.h:777
unit_t scale for representing decibel values.
Definition: base.h:2844
decibel_scale & operator=(const decibel_scale &)=default
constexpr decibel_scale(const T value) noexcept
Definition: base.h:2853
constexpr decibel_scale(const T value, std::true_type, Args &&...) noexcept
Definition: base.h:2855
constexpr decibel_scale()=default
T m_value
linearized value
Definition: base.h:2858
constexpr T operator()() const noexcept
Definition: base.h:2856
constexpr decibel_scale(const decibel_scale &)=default
~decibel_scale()=default
unit_t scale which is linear
Definition: base.h:2490
constexpr T operator()() const noexcept
returns value.
Definition: base.h:2501
UNIT_LIB_DEFAULT_TYPE m_value
linearized value.
Definition: base.h:2503
constexpr linear_scale(const linear_scale &)=default
linear_scale & operator=(const linear_scale &)=default
constexpr linear_scale()=default
default constructor.
~linear_scale()=default
constexpr linear_scale(const T &value, Args &&...) noexcept
constructor.
Definition: base.h:2500
Trait which tests whether a type is inherited from a decibel scale.
Definition: base.h:2440
Trait which tests whether a type is inherited from a linear scale.
Definition: base.h:2418
Trait which tests if a class is a base_unit type.
Definition: base.h:695
Trait which tests whether two container types derived from unit_t are convertible to each other.
Definition: base.h:1829
Trait which checks whether two units can be converted to each other.
Definition: base.h:1532
Trait which tests that class T meets the requirements for a non-linear scale.
Definition: base.h:1752
Trait that tests whether a type represents a std::ratio.
Definition: base.h:593
Trait which tests whether two types has the same non-linear scale.
Definition: base.h:2464
Traits which tests if a class is a unit
Definition: base.h:1867
Trait which tests whether type T is a unit_value_t with a unit type in the given category.
Definition: base.h:3072
Trait which tests whether a type is a unit_value_t representing the given unit type.
Definition: base.h:3060
Traits which tests if a class is a unit
Definition: base.h:721
adds two unit_value_t types at compile-time
Definition: base.h:3113
static constexpr const unit_t< unit_type > value() noexcept
Value of sum.
Definition: base.h:3128
divides two unit_value_t types at compile-time
Definition: base.h:3265
static constexpr const unit_t< unit_type > value() noexcept
Value of quotient.
Definition: base.h:3279
multiplies two unit_value_t types at compile-time
Definition: base.h:3215
static constexpr const unit_t< unit_type > value() noexcept
Value of product.
Definition: base.h:3229
raises unit_value_to a power at compile-time
Definition: base.h:3311
static constexpr const unit_t< unit_type > value() noexcept
Value of exponentiation.
Definition: base.h:3326
calculates square root of unit_value_t at compile-time
Definition: base.h:3358
static constexpr const unit_t< unit_type > value() noexcept
Value of square root.
Definition: base.h:3373
subtracts two unit_value_t types at compile-time
Definition: base.h:3162
static constexpr const unit_t< unit_type > value() noexcept
Value of difference.
Definition: base.h:3178
Stores a rational unit value as a compile-time constant.
Definition: base.h:3039
Units unit_type
Definition: base.h:3040
std::ratio< Num, Denom > ratio
Definition: base.h:3041
static constexpr const unit_t< Units > value()
Definition: base.h:3044
Type representing an arbitrary unit.
Definition: base.h:887
std::ratio_add< std::ratio_multiply< typename BaseUnit::conversion_ratio, Translation >, typename BaseUnit::translation_ratio > translation_ratio
Definition: base.h:895
std::ratio_multiply< typename BaseUnit::conversion_ratio, Conversion > conversion_ratio
Definition: base.h:893
units::traits::unit_traits< BaseUnit >::base_unit_type base_unit_type
Definition: base.h:892
std::ratio_add< typename BaseUnit::pi_exponent_ratio, PiExponent > pi_exponent_ratio
Definition: base.h:894
#define UNIT_LIB_DEFAULT_TYPE
Definition: base.h:59
#define UNIT_ADD_CATEGORY_TRAIT(unitCategory)
Macro to create the is_category_unit type trait.
Definition: base.h:372
typename std::enable_if< B, T >::type enable_if_t
Definition: base.h:317
FMT_INLINE auto format_to(OutputIt &&out, format_string< T... > fmt, T &&... args) -> remove_cvref_t< OutputIt >
Formats args according to specifications in fmt, writes the result to the output iterator out and ret...
Definition: base.h:2922
void void_t
Definition: base.h:343
auto format(wformat_string< T... > fmt, T &&... args) -> std::wstring
Definition: xchar.h:137