c++ Data serialization from templated class

Viewed 201

I have a situation where I want to define a templated class which is able to get several different base types, like int, char array, data structure or a string. I want then to serialize and transmit the data using a method which accepts a pointer to array of chars and a length parameters.

sendData(const void *, size_t);

template <typename T>
T myClass(T data)
{
   // cast data to char array; calculate the length if not given
   sendData(data, length);
}

What is the best way to cast the the data parameter and calculate the size? Is template specialization the best option to deal with a case where we only expect to have predefined list of data types for the template? I am looking for a solution using native C++ and no external serialization libraries, and also avoiding reinterpret_cast. Can anyone provide me basic implementation example?

And on the receiver side, is there a way how the receiver can determine and validate that the data received have the expected type, before doing the deserialization?

1 Answers

I would recommend using std::ostringstream.

#include <sstream>

template <typename T>
void myClassImpl(const T& data)
{
   std::ostringstream oss; 
   oss << data;
   sendData(oss.str());
}

Note: length can be retrieved from std::string

Edit: If you only want this to work for specific types than you can overload the my myClass function and have the same implementation using templates. See the example below.

void myClass(int data)
{
   myClassImpl(data);
}

Note: from C++17 you can also use variants

Related