c++ - 结构化绑定(bind)的用例是什么?

标签 c++ c++17 structured-bindings

C++17 标准引入了一个新的 structured bindings功能,最初是 proposed 2015年,其句法出现广泛discussed稍后。

当您查看文档时,就会想到它们的一些用途。

聚合分解

让我们声明一个元组:

std::tuple<int, std::string> t(42, "foo");

使用结构化绑定(bind)可以很容易地在一行中获得命名的元素拷贝:

auto [i, s] = t;

相当于:

auto i = std::get<0>(t);
auto s = std::get<1>(t);

int i;
std::string s;
std::tie(i, s) = t;

对元组元素的引用也可以轻松获得:

auto& [ir, sr] = t;
const auto& [icr, scr] = t;

所以我们可以使用所有成员都是公共(public)的数组或结构/类。

多个返回值

一种从函数中获取多个返回值的便捷方法紧随上述内容。

还有什么?

您能否提供一些其他可能不太明显的结构化绑定(bind)用例?它们还能如何提高 C++ 代码的可读性甚至性能?

备注

正如评论中提到的,结构化绑定(bind)的当前实现缺少一些功能。它们是非可变的,它们的语法不允许显式跳过聚合成员。 Here可以找到关于可变性的讨论。

最佳答案

Can you provide some other, possibly less obvious use cases for structured bindings? How else can they improve readability or even performance of C++ code?

更一般地说,您可以使用它来(让我说)解包一个结构并从中填充一组变量:

struct S { int x = 0; int y = 1; };

int main() {
    S s{};
    auto [ x, y ] = s;
    (void)x, void(y);
}

反过来说:

struct S { int x = 0; int y = 1; };

int main() {
    S s{};
    auto x = s.x;
    auto y = s.y;
    (void)x, void(y);
}

数组也是如此:

int main() {
    const int a[2] = { 0, 1 };
    auto [ x, y ] = a;
    (void)x, void(y);
}

无论如何,当您从函数返回结构或数组时,它也有效,您可能会争辩说这些示例属于您已经提到的同一组案例。


@TobiasRibizel 对答案的评论中提到的另一个很好的例子是遍历容器并轻松解包内容的可能性。
std::map:

为例
#include <map>
#include <iostream>

int main() {
    std::map<int, int> m = {{ 0, 1 }, { 2, 3 }};
    for(auto &[key, value]: m) {
        std::cout << key << ": " << value << std::endl;
    }
}

关于c++ - 结构化绑定(bind)的用例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45480824/

相关文章:

c++ - 有没有办法将标准输出设置为二进制模式?

c++ - 通过->语法c++从指针访问函数

c++ - Windows 上的 C++17 是否与 ubuntu 上的 C++17 一致?

c++ - 将指向成员函数的指针传递给模板

c++ - 结构化绑定(bind)的函数声明

c++ - 无法让 std::ignore 在范围内的结构化绑定(bind)中工作

c++ - 在 C++ 中逐字读取文件

c++ - gcc 中带有 const& 模板参数的错误?

c++ - 如何获得可调用类型的签名?

c++ - 未知自定义结构上的结构化绑定(bind)