Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to copy POD struct/vector of structs to vector<unsigned char>

normally I am using something like

copy((uint8_t*)&POD, (uint8_t*)(&POD + 1 ), back_inserter(rawData));

copy((uint8_t*)&PODVec[0], (uint8_t*)(&PODVec[0] + PODVec.size()), back_inserter(rawData));

but I am not huge fan of this solution. Any nicer way to do this?

like image 664
NoSenseEtAl Avatar asked Dec 19 '25 20:12

NoSenseEtAl


1 Answers

You could write a pair of helper functions to hide the ugly casts and pointer arithmetics:

template<typename T>
char* object_begin(T& obj)
{
    return
        &const_cast<char&>(
            reinterpret_cast<const volatile char&>(obj)
        );
}

template<typename T>
char* object_end(T& obj)
{
    return object_begin(obj) + sizeof(obj);
}

You'd use them like this:

vector<POD> vpod;
vector<unsigned char> vbytes;

copy(object_begin(vpod.front()),
     object_end(vpod.back()),
     back_inserter(vbytes));
like image 98
jrok Avatar answered Dec 22 '25 11:12

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!