getml / reflect-cpp

A C++20 library for fast serialization, deserialization and validation using reflection. Supports JSON, BSON, CBOR, flexbuffers, msgpack, TOML, UBJSON, XML, YAML / msgpack.org[C++20]
https://getml.github.io/reflect-cpp/
MIT License
1.11k stars 97 forks source link

Derived Struct (Nested Struct) #239

Open DapengFeng opened 1 week ago

DapengFeng commented 1 week ago

If I define a struct derived from the base struct rfl::Field, how can I implement the parser for the new struct?

liuzicheng1987 commented 1 week ago

I suppose you could try to write a custom parser (refer to the documentation).

But I think the bigger question is: Why do you want to do this?

DapengFeng commented 1 week ago

I don't want to implement the custom parser for the derived struct just because I'm lazy:)

liuzicheng1987 commented 1 week ago

OK, fair enough, but the question is what are you trying to do in the first place? Personally, I can't think of any good reason to inherit from rfl::Field...

DapengFeng commented 1 week ago

rfl::Field is just an example. I want to define a derived class from the base one without implementing the custom parser.

DapengFeng commented 1 week ago

I am a junior at reflect-cpp, and I want to learn it in depth. Do you have any advice? Hope to hear you :) @liuzicheng1987

DapengFeng commented 1 week ago

I am a junior at reflect-cpp, and I want to learn it in depth. Do you have any advice? Hope to hear you :) @liuzicheng1987

Especially the logic in the internal namespace.

DapengFeng commented 1 week ago

I don't want to implement the custom parser for the derived struct just because I'm lazy:)

A Tip:

option(REFLECT_CPP_C_ARRAYS_OR_INHERITANCE "Enable C arrays and inheritance" ON)
liuzicheng1987 commented 1 week ago

Hi @DapengFeng,

inheritance is a bit of a tricky topic. We use structured bindings to automatically access the fields and so far no one has thought of a way to do this with inheritance.

You might also want to take a look at rfl::Flatten. Maybe that would solve your problem.

DapengFeng commented 1 week ago

Thank you for your advice. I try to learn reflect-cpp .

DapengFeng commented 1 week ago

Can I use the operator[] to access the named field in the runtime?

liuzicheng1987 commented 1 week ago

@DapengFeng , sure:

https://github.com/getml/reflect-cpp/blob/main/docs/generic.md

You could try something like:

const auto obj = rfl::to_generic(my_struct).to_object().value();
obj["my_field"];