Created
July 3, 2016 18:13
-
-
Save judofyr/18cc1e9e4f48a13483c00d1c86e34cf5 to your computer and use it in GitHub Desktop.
Example of reflection in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define REFLECT(x) template<class R> void reflect(R& r) { r x; } | |
#include <string> | |
struct Person { | |
std::string name; | |
int age; | |
REFLECT( | |
("name", name) | |
("age", age) | |
) | |
}; | |
#include <iostream> | |
class JSONWriter { | |
std::ostream& output; | |
bool needsComma; | |
public: | |
JSONWriter(std::ostream& output) : output(output) | |
{} | |
template<class T> | |
auto write(T& obj) -> decltype(obj.reflect(*this), void()) { | |
output << "{"; | |
needsComma = false; | |
obj.reflect(*this); | |
output << "}"; | |
} | |
void write(int value) { | |
output << value; | |
} | |
void write(std::string& value) { | |
output << '"' << value << '"'; | |
} | |
template<class T> | |
JSONWriter& operator()(const char* name, T& field) { | |
if (needsComma) { | |
output << ","; | |
} | |
needsComma = true; | |
output << name << ":"; | |
write(field); | |
return *this; | |
} | |
}; | |
int main() { | |
JSONWriter json(std::cout); | |
Person me = { "Magnus Holm", 23 }; | |
json.write(me); | |
} | |
You should be able to use the same trick to reflect on fields, but you'd have to plug in a "real" JSON parser, parse the data into a hash-map-like structure and then fill out the data.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is pretty cool! I have been looking for a simple solution like this but couldn't find anywhere...
Do you think it would be possible to have the inverse operation, i.e given a well-formed json and a Person reference a method that would populate the correct attributes onto the given object?