# CommonUnits **Repository Path**: llongww/common-units ## Basic Information - **Project Name**: CommonUnits - **Description**: 常用计量单位库,提供单位转换和显示等便捷功能 - **Primary Language**: C++ - **License**: LGPL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2021-04-19 - **Last Updated**: 2025-08-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # CommonUnits CommonUnits是参照std::chrono所写的单位库(Header-only),为单位的转换和界面显示等提供方便。 与std::chrono不同的是,本库所有的单位基本类型为double,而不是整数。 >注意:需要支持C++20的编译器。 ## 1. 编译期的字符串实现 ```c++ constexpr CU::BasicFixedString kv("kV"); constexpr CU::BasicFixedString ohm("Ω"); static_assert(kv == ohm); // 断言失败 ``` ## 2. 标准单位 ```c++ CU::Kilohertz khz(1.0); CU::Hertz hz(1000.0); std::cout << (khz == hz) << std::endl; ``` ```c++ void print(const CU::Kilohertz& khz) { std::cout << khz << std::endl } int main() { print(CU::Megahertz(1.0)); // 1000kHz print(CU::Hertz(100)); // 0.1kHz return 0; } ``` ## 3. 动态单位转换 ```c++ std::cout << CU::Chrono::toUnit(1.0, "s") << std::endl; // 1000ms std::cout << CU::Chrono::toUnit(1.0, "ms") << std::endl; // 0.001s ``` ## 4. 单位自适应转换 ```cpp CU::Volt v(0.1); auto [value, unit] = CU::adjustUnit(v); std::cout << value << unit << std::endl; // 100mV ``` ```cpp CU::Volt v(10.0); auto [value, unit] = CU::adjustUnit(v); std::cout << value << unit << std::endl; // 10V ``` ```cpp CU::Volt v(1000.0); auto [value, unit] = CU::adjustUnit(v); std::cout << value << unit << std::endl; // 1kV ``` ```cpp CU::Volt v(1000000.0); auto [value, unit] = CU::adjustUnit(v); std::cout << value << unit << std::endl; // 1MV ``` ## 5. 时间单位转换为标准库时间单位 ```cpp std::cout << static_cast(CU::Seconds(2.0)) << std::endl; ``` ## 6. 时间单位转换为其它类型的ADL实现示例 ```cpp namespace CU { template inline void fromUnit(const CommonUnits<_Type, _Unit>& unit, std::string& dest) { dest = std::format("{}{}", unit.count(), unit.unit().data()); } } int main() { CU::Kilohertz khz(1.0); std::string dest = static_cast(khz); std::cout << dest << std::endl; // 1kHz return 0; } ```