I have defined my own class :
class Rectangle {
int width;
int height;
};
I want to convert any such class object to vector<unsigned char>
. I tried doing it for particular types, and then for any type:
template< typename T > std::vector< byte, sizeof(T) > to_bytes( const T& object ) {
std::vector< byte, sizeof(T) > bytes ;
const byte* begin = reinterpret_cast< const byte* >(std::addressof(object)) ;
const byte* end = begin + sizeof(T) ;
std::copy( begin, end, std::begin(bytes) ) ;
return bytes ;
}
But this is valid only for a particular type
in C++. How can I convert my Rectangle
class, or any user defined class for that matter to vector<unsigned char>
?