Hacker News new | ask | show | jobs
by wwright 2020 days ago
Isn’t that what templates and constexpr are?
1 comments

To a degree, but templates and constexpr don't support a bunch of features like compile-time field enumeration and introspection + code generation.

For example, let's say I have a bunch of structs:

  struct GeoCoordinate {
    int lat, long;
  };

  struct GeoArea {
    std::vector<GeoCoordinate> perimeter;
  };

  struct Place {
    std::string name;
    std::string contact_number;
    GeoArea area;
  };
Now I need to serialize these structs into a format to be sent over the wire. Currently, I have a few choices:

1. Use an off-the-shelf library like protobuf (disclaimer: I work for Google). Then I have to convert my code to a protobuf definition and rely on its code generator to perform [de]serialization. I also have to hope that my library supports all the field definitions I need.

2. Write macros to define each field in each structure. These macros perform some arcane magicks that somehow create the necessary [de]serialization functions. These macros are difficult to write and maintain (or I find a library).

3. Manually define the methods myself. This is tedious, hard to maintain, and error prone.

What if I could write some code in C++ which could read the structure and generate the appropriate serialization code? Something like (syntax hypothetical):

  Serializable(Class) {
    std::string serialize() {
      std::string output;
      for (auto member : Class.members()) { // loop unrolled at compile time
        if (member.type == int) {
          output.append(std::format("{:10}"), member.get())
        } else if (member.type == std::string) {
          ...
        } else if (member.type == std::vector) {
          ...
        } else if (std::has_metaclass_v<member.type, Serializable>) {
          output.append(member.get().serialize());
        }
      }
    };
  };

Then I could annotate my classes with Serializable instead.

See https://www.youtube.com/watch?v=4AfRAVcThyA.

Yeah static structural reflection is an important use-case. The main objection I’ve heard to standardization in C++ has to do with maintaining the mistake of conflating structs and classes and supporting C’s long broken unit type.