Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Capture of typed references to generic objects #337

Open
TheZoc opened this issue Jan 17, 2025 · 1 comment
Open

Capture of typed references to generic objects #337

TheZoc opened this issue Jan 17, 2025 · 1 comment

Comments

@TheZoc
Copy link

TheZoc commented Jan 17, 2025

Hello,

I was running some tests with the sample provided, and found out I can't bind a reference to a generic object without a reinterpret_cast.

Example code:

rfl::Generic::Object test;
test["name"] = "John Smith";
test["email"] = "[email protected]";
test["age"] = 40;

If I try to add an address like this, it works, as expected:

test["address"] = rfl::Generic::Object;
test["address"]["street"] = "123 High Street"; 
test["address"]["city"] = "London";
test["address"]["zip"] = "SE1 1AA"

But I'd like to store a reference to "address" key. This is how I managed to make it work:

test["address"] = rfl::Generic::Object;
auto& address = reinterpret_cast<rfl::Generic::Object&>(test["address"]);
address["street"] = "123 High Street"; 
address["city"] = "London";
address["zip"] = "SE1 1AA"

Is there a way to avoid reinterpret_cast?
If not, would such feature request fit in your roadmap?

Thank you in advance!

@liuzicheng1987
Copy link
Contributor

I will refer you to the documentation:

https://rfl.getml.com/generic/

You could make use of the fact that a Generic is really just a wrapper around a variant which you can retrieve using .variant() or .get():

auto& address = std::get_if<rfl::Object>(&test["address"].variant());

Just to be clear: If you know the keys of your fields at compile time, you would be much better off using structs. Not only is it more efficient, but it also helps you to avoid issues like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants