CMakeTutorialStep1 2.3.12
Loading...
Searching...
No Matches
ModernParadigm.hxx
Go to the documentation of this file.
1#pragma once
2
9
10#include <concepts>
11#include <cstdint>
12#include <expected>
13#include <span>
14#include <string_view>
15
16namespace tutorial {
17
19struct Price {
20 std::int64_t cents{};
21 friend constexpr bool operator==(Price, Price) = default;
22};
23
25struct Quantity {
26 std::int32_t value{};
27 friend constexpr bool operator==(Quantity, Quantity) = default;
28};
29
31enum class ParseErr : int { empty = 1, invalid = 2, overflow = 3 };
32
38[[nodiscard]] std::expected<Price, ParseErr> parse_price_cents(std::string_view s);
39
41[[nodiscard]] std::int64_t sum_cents(std::span<const Price> prices) noexcept;
42
44template <class T>
45concept NamedValue = requires(T t) {
46 { t.value } -> std::convertible_to<std::int32_t>;
47};
48
50template <NamedValue T>
51[[nodiscard]] constexpr std::int32_t raw_qty(T t) noexcept {
52 return t.value;
53}
54
55} // namespace tutorial
Concept 演示:具名数值类型须暴露 .value 且可转为 int32.
Definition ModernParadigm.hxx:45
Definition ModernParadigm.cxx:11
std::expected< Price, ParseErr > parse_price_cents(std::string_view s)
逐字符解析十进制整数分;空串、非数字或溢出返回对应 ParseErr
Definition ModernParadigm.cxx:14
constexpr std::int32_t raw_qty(T t) noexcept
提取 NamedValue 的原始数量值
Definition ModernParadigm.hxx:51
std::int64_t sum_cents(std::span< Price const > prices) noexcept
累加各 Price::cents; noexcept 便于 fuzz/bench 热路径
Definition ModernParadigm.cxx:33
ParseErr
价格字符串解析的可恢复错误码
Definition ModernParadigm.hxx:31
@ overflow
Definition ModernParadigm.hxx:31
@ empty
Definition ModernParadigm.hxx:31
@ invalid
Definition ModernParadigm.hxx:31
价格强类型(整型分),避免与 Quantity 静默混用
Definition ModernParadigm.hxx:19
std::int64_t cents
Definition ModernParadigm.hxx:20
friend constexpr bool operator==(Price, Price)=default
数量强类型(整型单位)
Definition ModernParadigm.hxx:25
friend constexpr bool operator==(Quantity, Quantity)=default
std::int32_t value
Definition ModernParadigm.hxx:26