C++实现消息发送机制&C++17新特性any

// 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
`std::any` 是 C++17 中引入的一个新特性,用于存储任意类型的值,因此如果你要使用 `std::any`,你需要使用 C++17 或更高版本的编译器。 如果你的编译器不支持 C++17,你可以使用其他的实现方式,例如使用模板来实现类似的功能。比如下面这个示例: ```cpp #include <iostream> #include <string> #include <typeindex> #include <unordered_map> #include <stdexcept> class Any { public: Any() : m_tpIndex(std::type_index(typeid(void))) {} Any(const Any& other) : m_ptr(other.Clone()), m_tpIndex(other.m_tpIndex) {} Any(Any&& other) : m_ptr(std::move(other.m_ptr)), m_tpIndex(other.m_tpIndex) {} template<typename T, typename = typename std::enable_if<!std::is_same<typename std::decay<T>::type, Any>::value, T>::type> Any(T&& value) : m_ptr(new Derived<typename std::decay<T>::type>(std::forward<T>(value))), m_tpIndex(typeid(typename std::decay<T>::type)) {} bool IsNull() const { return !bool(m_ptr); } template<class T> bool Is() const { return m_tpIndex == std::type_index(typeid(T)); } template<class T> typename std::decay<T>::type& AnyCast() { if (!Is<T>()) { throw std::runtime_error("can not cast " + std::string(m_tpIndex.name()) + " to " + std::string(typeid(T).name())); } auto derived = dynamic_cast<Derived<typename std::decay<T>::type>*>(m_ptr.get()); return derived->m_value; } Any& operator = (const Any& other) { if (m_ptr == other.m_ptr) { return *this; } m_ptr = other.Clone(); m_tpIndex = other.m_tpIndex; return *this; } private: struct Base { virtual ~Base() {} virtual std::unique_ptr<Base> Clone() const = 0; }; template<typename T> struct Derived : Base { template<typename U> Derived(U&& value) : m_value(std::forward<U>(value)) { } std::unique_ptr<Base> Clone() const { return std::unique_ptr<Base>(new Derived<T>(m_value)); } T m_value; }; private: std::unique_ptr<Base> Clone() const { if (m_ptr != nullptr) { return m_ptr->Clone(); } return nullptr; } std::unique_ptr<Base> m_ptr; std::type_index m_tpIndex; }; int main() { Any a = 1; std::cout << a.AnyCast<int>() << std::endl; a = std::string("hello"); std::cout << a.AnyCast<std::string>() << std::endl; try { a.AnyCast<int>(); } catch (const std::exception& e) { std::cout << e.what() << std::endl; } return 0; } ``` 这段代码定义了一个 `Any` 类,使用模板参数来存储任意类型的值,并在运行时动态判断类型。你可以像使用 `std::any` 一样使用 `Any` 类型的变量,例如调用 `AnyCast` 方法来获取存储的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

colorful_stars

您是我见过全宇宙最可爱的人!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值