Drake
Writing a Serialize method

Structured data sometimes provides a Serialize method to be compatible with a variety of readers, writers, or any other code that needs to visit the data generically.

Here is an example of implementing a Serialize method:

struct DoubleStruct {
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(value));
}
double value{0.0};
};

By convention, we place the Serialize method prior to the data members per the styleguide rule. Each data member has a matching Visit line in the Serialize method, in the same order as the member fields appear.

By convention, we declare all of the member fields as public, since they are effectively so anyway (because anything that calls the Serialize method receives a mutable pointer to them). The typical way to do this is to declare the data as a struct, instead of a class.

However, if the styleguide rule for struct vs class points towards using a class instead, then we follow that advice and make it a class, but we explicitly label the member fields as public. We also omit the trailing underscore from the field names, so that the Serialize API presented to the caller of the class is indifferent to whether it is phrased as a struct or a class.

For how Serialize and Archive interact, see the drake::yaml::YamlReadArchive class overview.