简体   繁体   中英

Generating code (including strings and derived identifiers) from the name of a struct and the names and types of its members

In the context of a library I am using, creating a type such as

struct my_name_t {
  int aaa;
  double bbb;
};

requires that the user also define and invoke

HF::CompoundType create_my_name_type() {
  return {{"aaa", HF::AtomicType<int>{}},
          {"bbb", HF::AtomicType<double>{}}};
}

HIGHFIVE_REGISTER_TYPE(my_name_t, create_my_name_type)

The second block is 100% boilerplate: every single character in the second block is a pure function of the contents of the first block. The only things that can vary are

  • the name of the struct,
  • the types and names of its members.

Everything else is fully-specified by this information.

What C++ metaprogramming techniques might be used to

  • generate the second block from the first, or
  • generate both from some common specification?

In the current C++ standard (C++20) there is no support for reflection, meaning, it is impossible to obtain a list of names and types of members.

(There were some discussions about adding "static reflection" to C++23 but not sure if this is still up-to-date.)

In praxis you can either write this redundant code or, if you are talking about many classes, typically generate it from some DSL (Domain Specific Language):

// file: X.struct

type X {
  x: int
  y: std::string
}
// file: X.generated.hpp

struct X {
  int x;
  std::string y;
};

// file: X.generated.cpp

static MyCustomReflectionType info()
{
    return {
      { "x", "int" },
      { "y", "std::string" },
    };
}

REGISTER_TYPE(X, info);

If you need to add custom methods, you would typically generate the base class and the implement the derived class yourself.

There are also some hybrid code/generation things you can do, where you can try to extract that info from C++ code, but you'll probably shoot yourself in the foot with that.

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