I have a basic message class that I am using to serialize data and then send that data through a socket:
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;
}
I know there are some possible bugs/errors in this code if these are called incorrectly, but I'm the only developer right now, and I need to get something working. Also, I'm assuming that only basic types will be passed, and that endiness is the same on both ends.
I want this message class to be able to handle structs. My thought was this: in each of my structs I will write a "Serialize/Deserialize" function. Then, in my LoadData and GetData calls, I will check if there is a "Serialize/Deserialize" function and then call it instead of doing the generic memcpy.
I was able to check if there is a serialize function using something similar to the code in this question: Check if a class has a member function of a given signature
But I'm not sure how I am suppose to call the "Serialize" function. I can't simply use "inData.Serialize()", as that fails to compile.
So in short, I want my LoadData Function to look something like this:
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);
}
}
Any help would be much appreciated.
NOTE: My boss does not like to add external libraries to project unless absolutely necessary. That's why I haven't gone with Protobuf or something similar.