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