AirlineTicket 1.0.12
Loading...
Searching...
No Matches
modern_paradigm.cppm
Go to the documentation of this file.
1
8
9export module modern_paradigm;
10
11import std;
12
13export namespace modern {
14
16struct Price {
17 std::int64_t cents{};
18 friend constexpr bool operator==(Price, Price) = default;
19};
20
22struct Quantity {
23 std::int32_t value{};
24 friend constexpr bool operator==(Quantity, Quantity) = default;
25};
26
28enum class ParseErr : int { empty = 1, invalid = 2, overflow = 3 };
29
31[[nodiscard]] std::expected<Price, ParseErr> parse_price_cents(std::string_view s) {
32 if (s.empty()) {
33 return std::unexpected(ParseErr::empty);
34 }
35 std::int64_t v = 0;
36 for (char c : s) {
37 if (c < '0' || c > '9') {
38 return std::unexpected(ParseErr::invalid);
39 }
40 int const d = c - '0';
41 if (v > (std::numeric_limits<std::int64_t>::max() - d) / 10) {
42 return std::unexpected(ParseErr::overflow);
43 }
44 v = v * 10 + d;
45 }
46 return Price{v};
47}
48
50[[nodiscard]] std::int64_t sum_cents(std::span<Price const> prices) noexcept {
51 std::int64_t s = 0;
52 for (Price p : prices) {
53 s += p.cents;
54 }
55 return s;
56}
57
58} // namespace modern
现代 C++ 范式演示(模块版):expected + 强类型 + span。
Definition modern_paradigm.cppm:13
std::int64_t sum_cents(std::span< Price const > prices) noexcept
对价格 span 求和(零拷贝)
Definition modern_paradigm.cppm:50
ParseErr
价格字符串解析的可恢复错误码
Definition modern_paradigm.cppm:28
@ overflow
Definition modern_paradigm.cppm:28
@ empty
Definition modern_paradigm.cppm:28
@ invalid
Definition modern_paradigm.cppm:28
std::expected< Price, ParseErr > parse_price_cents(std::string_view s)
解析 ASCII 数字分字符串;失败返回 ParseErr
Definition modern_paradigm.cppm:31
价格强类型(整型分)
Definition modern_paradigm.cppm:16
friend constexpr bool operator==(Price, Price)=default
std::int64_t cents
Definition modern_paradigm.cppm:17
数量强类型(整型单位)
Definition modern_paradigm.cppm:22
friend constexpr bool operator==(Quantity, Quantity)=default
std::int32_t value
Definition modern_paradigm.cppm:23