Bootstrap

C++17(1) : 结构化绑定(Structured Bindings)

1、结构化绑定

    结构化绑定允许通过对象、结构体的成员来初始化多个变量,例如

struct Mystruct{
    int i = 0;
    std::string s = "hello";
}

Mystruct ms;
auto [u, v] = ms;

2、用处

  a、通常用处

    结构化绑定通常应用与接收返回结构体、类对象、数组等包含多个元素的函数返回值。例如:

Mystruct GetStruct(){
    return Mystruct{42, "Hello structured bindings."};
}
auto [id, val] = GetStruct();
if(id > 30){
    std::cout << val << std::endl;
}

    优势在于直接访问这些成员变量,让代码有更好的可读性。

 

  b、更多用处及需要注意的细节

std::unordered_map<std::string, int> s_map{
    {"Hello", 1},{"World", 2}};

//优点:可读性更好。
void PrintMapOld(){
    std::cout << "This is old style." << std::endl;
    for(const auto& item : s_map){
        std::cout << item.first << " : " << item.second << std::endl;
    }
}

void PrintMapcpp17(){
    std::cout << "This is cpp17 style." << std::endl;
    for(const auto& [name, value] : s_map){
        std::cout << name << " : " << value << std::endl;
    }
}

struct B{
    int a = 1;
    int b = 2;
};

struct 
;