模板集合
clang-doc 文档
博客
AirlineTicket
1.0.12
Toggle main menu visibility
Loading...
Searching...
No Matches
modern_paradigm.cppm
Go to the documentation of this file.
1
8
9
export
module
modern_paradigm
;
10
11
import
std;
12
13
export
namespace
modern
{
14
16
struct
Price
{
17
std::int64_t
cents
{};
18
friend
constexpr
bool
operator==
(
Price
,
Price
) =
default
;
19
};
20
22
struct
Quantity
{
23
std::int32_t
value
{};
24
friend
constexpr
bool
operator==
(
Quantity
,
Quantity
) =
default
;
25
};
26
28
enum 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
modern_paradigm
现代 C++ 范式演示(模块版):expected + 强类型 + span。
modern
Definition
modern_paradigm.cppm:13
modern::sum_cents
std::int64_t sum_cents(std::span< Price const > prices) noexcept
对价格 span 求和(零拷贝)
Definition
modern_paradigm.cppm:50
modern::ParseErr
ParseErr
价格字符串解析的可恢复错误码
Definition
modern_paradigm.cppm:28
modern::ParseErr::overflow
@ overflow
Definition
modern_paradigm.cppm:28
modern::ParseErr::empty
@ empty
Definition
modern_paradigm.cppm:28
modern::ParseErr::invalid
@ invalid
Definition
modern_paradigm.cppm:28
modern::parse_price_cents
std::expected< Price, ParseErr > parse_price_cents(std::string_view s)
解析 ASCII 数字分字符串;失败返回 ParseErr
Definition
modern_paradigm.cppm:31
modern::Price
价格强类型(整型分)
Definition
modern_paradigm.cppm:16
modern::Price::operator==
friend constexpr bool operator==(Price, Price)=default
modern::Price::cents
std::int64_t cents
Definition
modern_paradigm.cppm:17
modern::Quantity
数量强类型(整型单位)
Definition
modern_paradigm.cppm:22
modern::Quantity::operator==
friend constexpr bool operator==(Quantity, Quantity)=default
modern::Quantity::value
std::int32_t value
Definition
modern_paradigm.cppm:23
CXX-CMake-template
CXX-CMake-template
single-exe-modules
src
modern_paradigm.cppm
Generated by
1.18.0