1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| #include <variant>
#include <string>
#include <vector>
#include <cstdint>
// 定义协议消息类型
struct LoginRequest {
std::string username;
std::string password;
};
struct MoveRequest {
float x, y, z;
uint32_t timestamp;
};
struct ChatMessage {
uint32_t channelId;
std::string content;
};
// variant 作为消息容器——类型安全,无堆分配
using GameMessage = std::variant<LoginRequest, MoveRequest, ChatMessage>;
// 消息处理器——编译期保证所有消息类型都被处理
class MessageHandler {
public:
void handle(const GameMessage& msg)
{
std::visit(overloaded{
[this](const LoginRequest& req) {
// 验证用户名密码
printf("Login: %s\n", req.username.c_str());
authenticatePlayer(req.username, req.password);
},
[this](const MoveRequest& req) {
// 更新玩家位置
printf("Move to (%.1f, %.1f, %.1f)\n", req.x, req.y, req.z);
updatePosition(req.x, req.y, req.z);
},
[this](const ChatMessage& msg) {
// 广播聊天
printf("Chat [%u]: %s\n", msg.channelId, msg.content.c_str());
broadcastChat(msg.channelId, msg.content);
}
}, msg);
}
private:
void authenticatePlayer(const std::string&, const std::string&) { /* ... */ }
void updatePosition(float, float, float) { /* ... */ }
void broadcastChat(uint32_t, const std::string&) { /* ... */ }
};
|