无法从字符串流接收信息

Can't receive info from string stream

本文关键字:信息 字符串      更新时间:2023-10-16

所以我试图使用std::stringstream将信息序列化为字符串,但编译器不喜欢我。

enum PacketType : unsigned int {
PacketType_unknown = 0,
PacketType_ping,
PacketType_server_welcome,
PacketType_client_greetings,
};
std::stringstream ss;
unsigned int v;
PacketType p;
ss << (unsigned int)somevalue;
// error here
ss >> p;

错误是:

no match for 'operator>>' (operand types are 'std::stringstream' {aka 
'std::__cxx11::basic_stringstream<char>'} and 'PacketType')GCC

编辑:忘记添加这么多东西,因为我认为这并不重要

我终于想通了,我的代码不起作用的原因是......

PacketType!=unsigned int. PacketType是它自己的类型。即使它基于unsigned int.

所以我所要做的就是

unsigned int s;
ss >> s;
somevalue = static_cast<PacketType>(s);

虽然还是很奇怪... 不应该PacketType继承unsigned int.