简体   繁体   中英

Read data from file into struct

I have a struct:

struct MyStruct
{
    uint16_t num_attributes;
    std::vector<attribute> attributes; //size of num_attributes
    uint16_t num_methods;
    std::vector<method> methods; //size of num_methods
    ...
}

I currently read into the members one at a time, just hardcoded. This means that if I make a change to the struct in the future, I'll have to do a complete overhaul of that code.

Is there a better way to autonomously read data into the struct?

Short answer: no

Long answer: Doing serialization automatically requires the language to support introspection so that the serialization library can see the structure it needs to serialize. C++ does not support introspection.

There are serialization libraries out there that automate some of the process for you. They all require you to still list each struct member, however.

For example, a library like Boost Serialization only makes you add code to serialize each member. The library handles recursion, writing collections, versioning, etc. Those benefits do add up, especially the versioning aspect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM