-
-
Notifications
You must be signed in to change notification settings - Fork 6.7k
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
[Request] Macro generating from_json() and to_json() #895
Comments
I also have little experience in this. You may want to have a look at cereal (http://uscilab.github.io/cereal/index.html) which employs some nice macro magic. |
Well, looks like I found a solution. It was inspired by a topic on StackOverflow #define REM(x) x
#define EAT(x)
#define MAKEQUOTES(x) #x
#define PLEASEMAKEQUOTES(x) MAKEQUOTES x
#define PRETTYPLEASEMAKEQUOTES(x) PLEASEMAKEQUOTES((x))
// Strip off the type
#define STRIP(x) EAT x
// Get the name of variable
#define NAMEOF(x) PRETTYPLEASEMAKEQUOTES(STRIP(x))
// Show the type without parenthesis
#define PAIR(x) REM x
#define JSONVARS1(a1) \
PAIR(a1);\
void _member_to_json(json& j) const { \
j = json{{ NAMEOF(a1), STRIP(a1) } \
};\
} \
void _member_from_json(const json& j){ \
STRIP(a1) = j.at(NAMEOF(a1)).get<decltype(STRIP(a1))>();\
}
#define JSONVARS2(a1, a2) \
PAIR(a1);\
PAIR(a2);\
void _member_to_json(json& j) const { \
j = json{{ NAMEOF(a1), STRIP(a1) }, \
{ NAMEOF(a2), STRIP(a2) } \
};\
} \
void _member_from_json(const json& j){ \
STRIP(a1) = j.at(NAMEOF(a1)).get<decltype(STRIP(a1))>();\
STRIP(a2) = j.at(NAMEOF(a2)).get<decltype(STRIP(a2))>();\
}
#define TO_JSON(MyClass) inline void to_json(json& j, const MyClass& p) {\
p._member_to_json(j);
#define FROM_JSON(MyClass) inline void from_json(const json& j, MyClass& p) {\
p._member_from_json(j);
//to match the style
#define END } Usage:
Feel free to use it. |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
Making to_json() and from_json() for all classes in my object model is a chore.
I want to create a macro that would generate bodies for these functions. I saw some clues how to make it, but my knowledge of C++ is not good enough to implement it.
I want to be able to write something like this:
and get
The text was updated successfully, but these errors were encountered: