3

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> ?

user17836
  • 103
  • 1
  • 7

1 Answers1

1

You could do this by making a user defined type conversion in Rectangle class:

explicit operator vector<unsigned char>() const {
// Do something here
}

Hope this helps.

Jake Freeman
  • 1,700
  • 1
  • 8
  • 15