订单方向枚举
Order Side Enum
题目详情
在低延迟交易系统中,类型安全至关重要,防止意外混淆买卖方向。使用强类型 scoped enum 约束订单方向,配合 constexpr 函数实现零开销转换。
任务:实现买卖方向 scoped enum(BUY/SELL),提供编译期字符转换函数。运行时零开销。
英文原题
In low-latency trading systems, type safety is critical to prevent the accidental mixing of order sides, prices, and quantities. Utilizing a strongly typed scoped enumeration for order sides enforces this safety, while a constexpr function allows the compiler to evaluate the opposite side at compile time to eliminate runtime overhead.
Task
Implement a scoped enumeration enum class OrderSide containing two values: Buy = 0 and Sell = 1. Then, write a constexpr function flipSide(OrderSide side) th
解析
问题分析
使用类型安全的枚举表示订单方向(买入/卖出/做空)可以避免将整数误传为订单方向的编译期错误。C++ enum class 配合 switch 穷举检查可确保所有方向都被处理。
实现
enum class OrderSide : uint8_t { BUY = 1, SELL = 2, SHORT = 3 };
inline std::string_view toString(OrderSide s) {
switch (s) {
case OrderSide::BUY: return "BUY";
case OrderSide::SELL: return "SELL";
case OrderSide::SHORT: return "SHORT";
}
return "UNKNOWN";
}
inline int sign(OrderSide s) { return (s == OrderSide::BUY) ? 1 : -1; }复杂度与边界
- 时间复杂度:toString O(1)
- 空间复杂度:O(1)
- 边界条件:(1) 从整数构造时验证范围 (2) switch 无 default 分支以便编译器警告未处理枚举值
英文解析
Analysis
Type-safe enums representing order direction (buy/sell/short) prevent compile-time errors from passing integers as order directions. C++ enum class with exhaustive switch checking ensures all directions are handled.
Solution
enum class OrderSide : uint8_t { BUY = 1, SELL = 2, SHORT = 3 };
inline std::string_view toString(OrderSide s) {
switch (s) {
case OrderSide::BUY: return "BUY";
case OrderSide::SELL: return "SELL";
case OrderSide::SHORT: return "SHORT";
}
return "UNKNOWN";
}
inline int sign(OrderSide s) { return (s == OrderSide::BUY) ? 1 : -1; }Complexity & Edge Cases
- Time complexity: toString O(1)
- Space complexity: O(1)
- Edge cases: (1) Validate range when constructing from integer (2) No default branch in switch enables compiler warnings for unhandled enum values
Key Considerations
- Explicit underlying type: Use enum class : uint8_t for compact serialization; never rely on default int-sized underlying type for wire protocol
- Bid/Ask vs Buy/Sell: Side must distinguish direction (buy vs sell) from market position (bid vs ask); buy = bid side, sell = ask side in standard convention
- Serialization mapping: Map enum values to FIX Side values (1=Buy, 2=Sell) and binary protocol codes; provide bidirectional conversion functions
- Invalid value handling: Decoder must reject unknown side values; treat as error, not default to Buy — wrong side causes incorrect position accumulation