I'm trying to store my struct into txt file using boost but unable to do it. I'm using boost library. example structure
struct Frame
{
uint32_t address{ 0 };
uint16_t marks{ 0 };
uint16_t age{ 0 };
char gender{ 'M' };
std::string userName;
};
for binary there is simple code
boost::archive::binary_oarchive ar(ofs, boost::archive::no_header);
ar << boost::serialization::make_binary_object(&f, sizeof(Frame));
assume file is open with fstream object ofs and 'f' is object of 'Frame'
I want to know if there is similar way to write structure to txt file and I do not want to write data types one by one. assume we don't know the types/number of datatypes inside structure.
As others have commented you will have to provide serialization helpers that tell Boost how to member-wise serialize.
If you have only aggregates like this, you can automate the generation of this function to a degree with Boost PFR:
Here's an example:
Note I stick them in a namespace for good style and also so we can highlight that ADL is used to find a
serializeoverload. Now let's define the overloads:Using the macro we avoid repeated code. Of course you could do this without a macro as well.
Now you can serialize both. Let's say we have:
Then serializing to a text stream:
Already results in the stream containing e.g.
Full Demo
This demo checks that the result of deserializing is actually identical to the original structs:
Live On Coliru
Prints