Any sort of reflection brings C++ one step closer to Python.
Implementing serialization for complex types often requires manual code writing or external tools. With static reflection you could automate this process
template<typename T>
void serialize(const T& obj, std::ostream& os) {
for_each(reflect(T), [&](auto member) {
os << member.name() << ": " << member.get(obj) << "\n";
});
}
Simplified property systems
class Person {
public:
Person(const std::string& name, int age)
: name(name), age(age) {}
std::string getName() const { return name; }
void setName(const std::string& name) { this->name = name; }
int getAge() const { return age; }
void setAge(int age) { this->age = age; }
private:
std::string name;
int age;
REFLECT_PROPERTIES(
(name, "Name of the person"),
(age, "Age of the person")
)
};
int main() {
Person person("Alice", 30);
auto properties = reflect::getProperties<Person>();
for (const auto& prop : properties) {
std::cout << "Property: " << prop.name
<< " (" << prop.description << ")" << std::endl;
auto value = reflect::get(person, prop.name);
std::cout << "Value: " << value << std::endl;
if (prop.name == "age") {
reflect::set(person, prop.name, 31);
}
}
std::cout << "Updated age: " << person.getAge() << std::endl;
return 0;
}
Simplified template metaprogramming
template<typename T>
void printTypeInfo() {
constexpr auto info = reflect(T);
std::cout << "Type name: " << info.name() << "\n";
std::cout << "Member count: " << info.members().size() << "\n";
}
Easier to write generic algorithms that work with arbitrary types
template<typename T>
void printAllMembers(const T& obj) {
for_each(reflect(T), [&](auto member) {
std::cout << member.name() << ": " << member.get(obj) << "\n";
});
}