I'm writing a function for a class that serializes structs representing packets to a single buffer, which is then sent to players in a multiplayer game. To keep this function as generic as possible, I though it would be a good idea to reserve a buffer for containing the structs and provide a template function that will construct the struct on the buffer and return a reference to it. Here is what I've tried...
template <typename T>
T& writePacket()
{
auto addr = m_writeOffset;
*m_writeOffset = T();
m_writeOffset += sizeof(T);
return *addr;
}
Where m_writeOffset is a u8* pointer to the next available byte.
I'm certain that returning a pointer to the location in the buffer where the struct lies would be much easier, however each of my packet struts contain a static byte for the header, which allows the clients to identify the packet types. Here are a few examples of some packets I might send:
typedef u8 packet_header;
#pragma pack(push, 1)
struct CP_AttackEntity
{
static const packet_header header = 0;
u16 targetUID;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct CP_EntityMoved
{
static const packet_header header = 3;
u16 uid;
Vec2<u16> pos;
};
#pragma pack(pop)
u8, u16, are just typedefs for uint8_t, etc.
I guess the reason why this isn't working comes from me not fully understanding how constructors work. When the packet is sent by the server or received by a client, the packets is entirely zeroed out. Can someone point me in the right direction? Thanks!