C++遍历结构体中的属性
#include <iostream> #include <type_traits> #include <unordered_map> #include <variant> using namespace std; struct Person{ std::size_t age; std::size_t height; std::string name; }; using PersonField = std::variant<std::size_t Person::*, std::string Person::*>; // 可以通过宏元编程来简化 std::unordered_map<std::string_view, PersonField> infos{ { "age", &Person::age }, { "height", &Person::height }, { "name", &Person::name } }; int main() { std::cout << "Hello World!\n"; Person p{ 10, 20, "John" }; for(auto&& [name, value] : infos){ auto name1 = name; // 这里为什么不能直接捕获 name,待确认? std::visit([=](auto&& field){ std::cout << name1 << ": " << p.*field << '\n'; }, value); } }
使用for循环和结构化绑定可以将结构体成员的遍历转化为遍历一个map的键值对,具体的实现方式如下:
struct MyStruct { int a; double b; std::string c; }; MyStruct my_struct = {1, 2.0, "hello"}; for (auto&& [key, value] : std::as_const(my_struct)) { std::cout << key << ": " << value << std::endl; }
https://mp.weixin.qq.com/s/NZ6DZFOrcicskMqPYKiLzw