【发布时间】:2017-11-29 19:02:50
【问题描述】:
我有一个基本的消息类,用于序列化数据,然后通过套接字发送该数据:
std::vector<char> m_rawMessageData;
int m_currentReadPosition = 0;
template<typename writeDataType>
void LoadData(writeDataType &inData)
{
int dataSize = sizeof(writeDataType);
int currentSize = m_rawMessageData.size();
m_rawMessageData.resize(dataSize + m_rawMessageData.size());
std::memcpy(&m_rawMessageData.at(currentSize), &(inData), dataSize);
}
template<typename ReadDataType>
int GetData(ReadDataType &outData)
{
std::stringstream dataReader;
int dataSize = sizeof(ReadDataType);
if (m_currentReadPosition + dataSize > m_rawMessageData.size())
return 0;
std::memcpy(&outData, &m_rawMessageData.at(m_currentReadPosition),
dataSize);
m_currentReadPosition += dataSize;
return dataSize;
}
我知道如果调用不正确,此代码中可能存在一些错误/错误,但我是目前唯一的开发人员,我需要让某些东西正常工作。另外,我假设只会传递基本类型,并且两端的 endiness 是相同的。
我希望这个消息类能够处理结构。我的想法是:在我的每个结构中,我将编写一个“序列化/反序列化”函数。然后,在我的 LoadData 和 GetData 调用中,我将检查是否存在“Serialize/Deserialize”函数,然后调用它而不是执行通用 memcpy。
我能够使用与此问题中的代码类似的东西来检查是否有序列化函数: Check if a class has a member function of a given signature
但我不确定我应该如何调用“序列化”函数。我不能简单地使用“inData.Serialize()”,因为它无法编译。
简而言之,我希望我的 LoadData 函数看起来像这样:
template<typename writeDataType>
void LoadData(writeDataType &inData)
{
//Check if writeDataType has Serialize Function.
if (serializeDoesExist)
{
inData.Serialize(m_rawMessageData);
}
else
{
int dataSize = sizeof(writeDataType);
int currentSize = m_rawMessageData.size();
m_rawMessageData.resize(dataSize + m_rawMessageData.size());
std::memcpy(&m_rawMessageData.at(currentSize), &(inData), dataSize);
}
}
任何帮助将不胜感激。
注意:除非绝对必要,否则我的老板不喜欢将外部库添加到项目中。这就是为什么我没有使用 Protobuf 或类似的东西。
【问题讨论】:
标签: c++ serialization