【新特性】C++17的结构化绑定语法详解

基本介绍

  1. 基本语法
    结构化绑定的语法是:

    auto [var1, var2, ...] = expr;
    
    • expr是一个返回类或结构的表达式
    • var1,var2是接收字段的变量名
    • 变量数量和顺序必须和expr的字段一致
  2. 自动类型推导
    结构化绑定会根据expr中的字段类型,自动为每个var推导出对应的类型。

  3. 嵌套结构支持
    如果expr的字段也是一个包含多个字段的结构,可以进一步嵌套解构:

    struct Inner {
          
          
      int a, b;
    };
    
    struct Outer {
          
          
      int c; 
      Inner inner;
    };
    
    Outer ret...;
    auto [c, [a, b]] = ret; // 嵌套解构 Inner
    
  4. 省略变量名
    可以用_省略不需要的变量:

    auto [a, _, c] = expr; // 忽略第二个字段
    
  5. 配合其他语法
    结构化绑定可以配合if/switch/for等语句:

    if(auto [x, y] = getPoint(); x > 0 && y > 0) {
          
          
      // 使用x,y
    }
    
    for(auto [k, v] : map) {
          
          
      // 使用k,v 
    }
    
  6. 返回引用
    如果expr返回引用,则解构的字段也会是引用。

  7. 用途
    结构化绑定非常适合用于从函数返回结构后进行解构,可以简化代码,避免创建临时变量。

不同数据类型的使用举例

Tuples

#include <tuple>

std::tuple<int, double, std::string> getTuple() {
    
    
    return std::make_tuple(42, 3.14, "Hello");
}

int main() {
    
    
    auto [intValue, doubleValue, stringValue] = getTuple();
    // Now you can use intValue, doubleValue, and stringValue as separate variables.
    return 0;
}

Arrays

int main() {
    
    
    int arr[] = {
    
    1, 2, 3, 4, 5};
    auto [a, b, c, d, e] = arr;
    // Now you can use a, b, c, d, and e as separate variables containing the elements of the array.
    return 0;
}

Pair

#include <utility>

std::pair<int, double> getPair() {
    
    
    return std::make_pair(42, 3.14);
}

int main() {
    
    
    auto [key, value] = getPair();
    // Now you can use key and value as separate variables.
    return 0;
}

引用传递

int main() {
    
    
    int x = 42, y = 23;
    auto& [rx, ry] = std::tie(x, y);
    
    // Now rx and ry are references to x and y, respectively.
    
    rx = 100;
    // This will modify the original value of x to 100.
    
    return 0;
}

元素忽略

std::tuple<int, double, std::string> getTuple() {
    
    
    return std::make_tuple(42, 3.14, "Hello");
}

int main() {
    
    
    auto [intValue, _, stringValue] = getTuple();
    // Here, we're ignoring the second element (doubleValue) of the tuple.
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40145095/article/details/131913006