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/