-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
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
Issue when dumping a vector of derived classes #4462
Comments
Do not use curly braces to initialize a JSON value, see the first item of the FAQ: https://json.nlohmann.me/home/faq/ |
I did the changes , but the issue persists. It seems like the to_json() function in the derived class is never called. See new code: https://godbolt.org/z/b9f7eezT9 |
That's correct, you have I believe that there's an example of this in the docs. |
Hi myermo,according to the new code you shared at https://godbolt.org/z/b9f7eezT9, I believe I understand the effect you're aiming for, you actually expecting the type of member v in Container could have polymorphism behavior: when you passed a Derived* type to the Container constructor, you thought the member v could be constructed as vector<Derived*>. That's not gonna happen because std::vector does not support that kind of behavior. So the Actual Result is correct. Polymorphism in C++ applies only to the invocation of virtual functions, so the type of member v in Container will always be vector<Base*> and the vector knows nothing about Derived*, that's why to_json() function in the derived class never be called. I think maybe you can re-define the Container as a template as well as related to_json function.
|
Description
I need to serialize a vector composed by derived classes. I have a
Container
class which holds two variables, one of them being astd::vector<Base>
. When dumping the contents of the vector, only the members of theBase
class are detected, and the members of the Derived classes are omitted.Reproduction steps
Just execute the example provided.
https://godbolt.org/z/KbxKs688Y
Expected vs. actual results
Actual Result
{ "Container": { "a": 2, "data": [ { "b": 3 }, { "b": 5 } ] } }
Expected Result
{ "Container": { "a": 2, "data": [ { "b": 3, "d": 4 }, { "b": 5, "d": 6 } ] } }
Minimal code example
Compiler and operating system
Arch Linux, GCC 14.2.1 and CLANG 19.1.0
Library version
b36f4c4
Validation
develop
branch is used.The text was updated successfully, but these errors were encountered: