Skip to content

Instantly share code, notes, and snippets.

@judofyr
Created July 3, 2016 18:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save judofyr/18cc1e9e4f48a13483c00d1c86e34cf5 to your computer and use it in GitHub Desktop.
Save judofyr/18cc1e9e4f48a13483c00d1c86e34cf5 to your computer and use it in GitHub Desktop.
Example of reflection in C++
#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);
}
@caiocsabino
Copy link

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?

@judofyr
Copy link
Author

judofyr commented Feb 1, 2022

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