// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <queue>
#include <functional>
#include <memory>
#include<string>
#include<unordered_map>
#include <string_view> // 使用 C++17 新增的 std::string_view
#include<any>
using namespace std;
// 定义消息类型的枚举
enum class MessageType {
CHAT_MESSAGE,
MOVE_MESSAGE,
};
// 定义消息结构体
struct ChatMessage {
string sender;
string receiver;
string content;
};
struct MoveMessage {
int playerId;
float moveDirection;
float moveSpeed;
};
// 定义消息类型
using MessageData = shared_ptr<void>;
// 定义消息结构体
struct Message {
MessageType type;
MessageData data;
};
// 消息队列
queue<Message> messageQueue;
// 注册消息处理函数的容器
unordered_map<MessageType, function<void(const Message&)>> messageHandlers;
// 发送消息函数
void sendMessage(const Message& msg) {
messageQueue.push(msg);
}
// 注册消息处理函数
void registerMessageHandler(MessageType type, function<void(const Message&)> handler) {
messageHandlers[type] = handler;
}
// 处理消息的函数
void processMessages() {
while (!messageQueue.empty()) {
Message msg = messageQueue.front();
messageQueue.pop();
// 查找并调用相应的消息处理函数
auto it = messageHandlers.find(msg.type);
if (it != messageHandlers.end()) {
it->second(msg);
}
}
}
// 示例的消息处理函数
void handleChatMessage(const Message& msg) {
const ChatMessage& chatMsg = *(static_pointer_cast<ChatMessage>(msg.data));
cout << "Received Chat Message - Sender: " << chatMsg.sender
<< ", Receiver: " << chatMsg.receiver
<< ", Content: " << chatMsg.content << endl;
}
void handleMoveMessage(const Message& msg) {
const MoveMessage& moveMsg = *(static_pointer_cast<MoveMessage>(msg.data));
cout << "Received Move Message - Player ID: " << moveMsg.playerId
<< ", Direction: " << moveMsg.moveDirection
<< ", Speed: " << moveMsg.moveSpeed << endl;
}
class MyClass {
public:
MyClass() {}
// 设置值为数字
void setNumber(int num) {
value_ = num;
}
// 设置值为字符串
void setString(const string& str) {
value_ = str;
}
// 获取存储的值
any getValue() const {
return value_;
}
private:
any value_;
};
int main()
{
// 注册消息处理函数
registerMessageHandler(MessageType::CHAT_MESSAGE, handleChatMessage);
registerMessageHandler(MessageType::MOVE_MESSAGE, handleMoveMessage);
// 发送消息
Message chatMsg;
chatMsg.type = MessageType::CHAT_MESSAGE;
chatMsg.data = make_shared<ChatMessage>(ChatMessage{ "Alice", "Bob", "Hello Bob!" });
sendMessage(chatMsg);
Message moveMsg;
moveMsg.type = MessageType::MOVE_MESSAGE;
moveMsg.data = make_shared<MoveMessage>(MoveMessage{ 1, 90.0f, 5.0f });
sendMessage(moveMsg);
// 处理消息
processMessages();
MyClass obj;
// 设置值为数字
obj.setNumber(42);
// 获取并打印数字值
cout << "Value as Number: " << any_cast<int>(obj.getValue()) << endl;
// 设置值为字符串
obj.setString("Hello, C++17!");
// 获取并打印字符串值
cout << "Value as String: " << any_cast<string>(obj.getValue()) << endl;
return 0;
system("pause");
return 0;
}
C++实现消息发送机制&C++17新特性any
于 2023-08-07 23:10:22 首次发布