结构化绑定语法是否可以在多态 lambda 中使用

Can the structured bindings syntax be used in polymorphic lambdas

本文关键字:lambda 多态 绑定 语法 是否 结构化      更新时间:2023-10-16

>结构化绑定使遍历具有基于范围的 for 循环的映射更加清晰易读,如下所示

for (auto [key, value] : map) {
cout << key << " : " << value << endl;
}

但是,结构化绑定是否可以在如下所示的 lambda 表达式中使用?

std::for_each(map.begin(), map.end(), [](auto [key, value]) {
cout << key << " : " << value << endl;
});

从表面上看,上面的代码不适用于我 https://wandbox.org/permlink/sS6r7JZTB3G3hr78 在这里找到的在线C++编译器。

如果它不起作用,那么是否有充分的理由不支持上述内容? 还是只是尚未提出的东西? 模板只会在使用时实例化,因此结构化绑定的"取消绑定"过程可能发生在请求实例化的地方(即调用函数时(

语法目前不允许这样做;结构化绑定是一个简单的声明

简单声明:[...]
- 属性说明符-seq optdecl-specifier-seq ref-qualifieropt[标识符列表]初始值设定项;

而函数参数是由参数声明列表引入的,其中包含声明符s:

声明符指定这些实体的名称,并(可选(使用运算符(如*(指针(和()(函数返回((修改说明符的类型。

也就是说,结构化绑定是一种(块级(语句语法 - 您可以通过注意它的语法以分号结尾来看到这一点;.在 lambda 参数列表中允许结构化绑定需要添加其他语法。

这听起来是个好主意,我不能立即看到语法中的任何歧义;当然值得讨论,因为它比替代方案更简洁地解决了您提出的用例。

我认为这将是一个很好的建议(如果还没有的话(,它将简化传递 zip 迭代器/引用元组的算法的代码。(例如 https://github.com/correaa/iterator-zipper(

同时,似乎这不是您无法通过提取函数第一行中的结构来使用更冗长的代码来实现的:

#include <algorithm>
#include <iostream>
#include <map>
using std::cout;
using std::endl;
int main(){
auto map = std::map<int, int>{{1, 2}};
std::for_each(map.begin(), map.end(), [](auto const& key_value){
auto const& [key, value] = key_value;
cout<< key <<" "<< value <<endl;
});
}

https://wandbox.org/permlink/sS6r7JZTB3G3hr78

(这加强了这是可实现的并且易于添加到语言中的观点(。

更简化的版本可以缩进为:

[](auto const& _){auto&& [key, value] = _; // [](auto const& [key, value]){
cout<< key <<" "<< value <<endl;
}