lundi 27 avril 2015

Derive from std:string to add typedefs and enums

For UDP packages exchanged between client and server I would like to support two kinds of string fields:

  • null-terminated c-string named cstring
  • string with preceeding uint8_t size-field named vstring

To self-document the layout of our packages I would like to use simple struct declarations:

struct ABC {
  vstring a;
  cstring b;
}

And call overloaded functions get(char*, vstring& v) and get(char*, cstring&) inside de/serialization function like this:

void deserialize(const char* bytes, ABC& msg) {
  get(msg.a);
  get(msg.b);
}

void serialize(char* bytes, const ABC& msg) {
  put(msg.a);
  put(msg.b);
}

However, for the user vstring and cstring should ideally behave just like normal std::string.

My first idea was to simply make std::string a public base of vstring and cstring such that the two classes can be disriminated during overload-resolution but behave the same for the user. But since deriving from std::string is discouraged, I am unsure what to do.

Aucun commentaire:

Enregistrer un commentaire