C++遍历结构体中的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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的键值对,具体的实现方式如下:

1
2
3
4
5
6
7
8
9
10
11
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

 

posted @   皮卡啰  阅读(137)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
点击右上角即可分享
微信分享提示