Logo
Section 1 / 11

作用域枚举与强类型

学习如何通过使用现代作用域枚举(enum class)替换传统的枚举,来强制类型安全、防止命名冲突并控制内存使用。

导入

作用域枚举与强类型

学习如何通过使用现代作用域枚举(enum class)替换传统的枚举,来强制类型安全、防止命名冲突并控制内存使用。

1#include <iostream> 2 3enum Color { 4 Red, 5 Green, 6 Blue 7}; 8 9enum TrafficLight { 10 Stop = 0, 11 Go = 1 12 // Red = 2 // Compilation Error: 'Red' is already defined by Color 13}; 14 15int main() { 16 Color paint = Red; 17 TrafficLight signal = Stop; 18 19 // PROBLEM: Implicit conversion allows meaningless comparisons 20 if (paint == signal) { 21 std::cout << "Red paint equals Stop signal? This shouldn't happen.\n"; 22 } 23 24 // PROBLEM: Nonsensical arithmetic 25 int result = paint + 10; 26 std::cout << "Paint + 10 is: " << result << "\n"; 27 28 return 0; 29}
1#include <iostream> 2 3// 'enum class' defines a scoped enumeration 4enum class Color { 5 Red, 6 Green, 7 Blue 8}; 9 10enum class TrafficLight { 11 Red, // No conflict! This is TrafficLight::Red 12 Green, 13 Yellow 14}; 15 16int main() { 17 Color paint = Color::Red; 18 TrafficLight signal = TrafficLight::Red; 19 20 // if (paint == signal) {} // Compilation Error: Cannot compare different types 21 // int x = paint; // Compilation Error: Cannot implicitly convert to int 22 23 if (paint == Color::Red) { 24 std::cout << "The paint is Red.\n"; 25 } 26 27 std::cout << "Scoped enums prevent accidental type mixing.\n"; 28 29 return 0; 30}
1#include <iostream> 2#include <cstdint> // For fixed-width types 3 4// Backed by an 8-bit unsigned integer (1 byte) 5enum class Status : uint8_t { 6 OK = 0, 7 Warning = 10, 8 Error = 20 9}; 10 11// Backed by a 64-bit unsigned integer 12enum class BigId : uint64_t { 13 ItemA = 0xFFFFFF, 14 ItemB = 0xAAAAAA 15}; 16 17int main() { 18 Status s = Status::OK; 19 20 std::cout << "Size of Status enum: " << sizeof(s) << " byte(s)\n"; 21 std::cout << "Size of BigId enum: " << sizeof(BigId::ItemA) << " bytes\n"; 22 23 return 0; 24}
1#include <iostream> 2#include <utility> // For std::to_underlying (C++23) 3 4enum class HTTPCode { 5 OK = 200, 6 NotFound = 404, 7 ServerError = 500 8}; 9 10void log_code(int code) { 11 std::cout << "Logging code: " << code << "\n"; 12} 13 14int main() { 15 HTTPCode response = HTTPCode::NotFound; 16 17 // Option 1: static_cast (Verbally explicit) 18 int code_val = static_cast<int>(response); 19 log_code(code_val); 20 21 // Option 2: std::to_underlying (C++23, cleaner) 22 // Automatically detects that the underlying type is int 23 auto val = std::to_underlying(response); 24 std::cout << "Using to_underlying: " << val << "\n"; 25 26 return 0; 27}
1#include <iostream> 2 3enum class ConnectionMode { 4 Secure, 5 Insecure 6}; 7 8enum class TimeoutPolicy { 9 Retry, 10 FailFast 11}; 12 13// Clear, readable parameters 14void connect(ConnectionMode mode, TimeoutPolicy policy) { 15 if (mode == ConnectionMode::Secure) { 16 std::cout << "Initializing SSL...\n"; 17 } 18 19 if (policy == TimeoutPolicy::Retry) { 20 std::cout << "Will retry on timeout.\n"; 21 } 22} 23 24int main() { 25 // Self-documenting function call 26 connect(ConnectionMode::Secure, TimeoutPolicy::FailFast); 27 28 // Compare this to: connect(true, false); -> What did true mean? 29 30 return 0; 31}

构建更大的程序

Lambdas 和函数式风格