jeudi 18 juin 2020

C++: best practice for loading and storing objects from and to text file [closed]

Suppose we have a number of classes with a hierarchy: at the bottom there are only built-in types. As an example, we have struct Store {Owner owner; int numItems; int priceItems;}; where the owner is another class struct Owner {string name; int age; };. If we were to store and load these parameters into and from a text file, namely JSON, what is the best programming pattern in C++?

The easiest solution is to implement a to and from function for each class to handle the IO. The main problem I have with this approach is that at some point, one relies on string constants to read or write text. This works fine with a few parameters and classes, but as soon as the number grows, it becomes more likely to make mistakes.

Ideally, all the code for IO can be done in one place, say a base class, and the other classes simply derive or use the base class to handle IO. I was wondering if there is some software pattern, or some new C++ standard that would make this less error-prone? I'm looking for native C++ solution, without relying on external libraries.

Aucun commentaire:

Enregistrer un commentaire