3.5 KiB
tags
| tags | ||
|---|---|---|
|
hello_units
!!! example "Try it on Compiler Explorer"
This is a really simple example showcasing the features of the mp-units library.
First, we include the headers for:
- a system of quantities (ISQ)
- symbols of SI units
- symbols of international units
- text and stream output support
--8<-- "example/hello_units.cpp:28:39"
Also, to shorten the definitions, we "import" mp_units namespace.
--8<-- "example/hello_units.cpp:40:41"
Next we define a simple function that calculates average speed based on the provided arguments of length and time:
--8<-- "example/hello_units.cpp:42:45"
The above function template takes any quantities implicitly convertible to isq::length
and isq::time respectively. Those quantities can use any compatible unit and a
representation type. The function returns a result of a really simple equation and ensures
that its quantity type is implicitly convertible to isq::speed.
!!! tip
Besides verifying the type returned from the function, constraining a generic return
type is really useful for users of such a function as it provides more information
of what to expect from a function than just using `auto`.
--8<-- "example/hello_units.cpp:47:50"
The above lines explicitly opt-in to use unit symbols from two systems of units. As this introduces a lot of short identifiers into the current scope, it is not done implicitly while including a header file.
--8<-- "example/hello_units.cpp:52:58"
- Lines
16&17create a quantity of kindisq::length / isq::timewith the numbers and units provided. Such quantities can be converted or assigned to any other quantity with a matching kind. - Line
18calls our function template with quantities of kindisq::lengthandisq::timeand number and units provided. - Line
19explicitly provides quantity types of the quantities passed to a function template. This time those will not be quantity kinds anymore and will have more restrictive conversion rules. - Line
20changes the unit of a quantityv3tom / sin a value-preserving way (floating-point representations are considered to be value-preserving). - Line
21does a similar operation but this time it would succeed also for value-truncating cases (if it was the case). - Line
22does a value-truncating conversion of changing the underlying representation type fromdoubletoint.
--8<-- "example/hello_units.cpp:60"
The above presents various ways to print a quantity.
Both stream insertion operations and std::format are supported.
!!! tip
`MP_UNITS_STD_FMT` is used for compatibility reasons. In case a specific compiler
does not support `std::format` or a user prefers to use `{fmt}` library, this macro
will resolve to `fmt` namespace. Otherwise, `std` namespace will be used.