结构化绑定语法是否可以在多态 lambda 中使用
Can the structured bindings syntax be used in polymorphic lambdas
>结构化绑定使遍历具有基于范围的 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;
}
- 多态性和功能结合
- 具有默认模板参数的多态类的模板推导失败
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 多态二进制函数
- 访问存储在向量C++中的结构的多态成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 将 std::allocate_shared 与多态资源分配器一起使用
- 通过switch和static_cast访问多态对象的运行时类型
- C++boost序列化多态性问题
- 多态杆件变量 - 类设计
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 结构化绑定语法是否可以在多态 lambda 中使用
- 有没有优雅的方法可以在多态 lambda 中编写类型别名
- 多态性在 lambda 函数C++不起作用
- 这种递归多态 C++1y lambda 调用有什么问题?
- 用C++lambda包装C回调,可以使用模板多态性
- 可能的 gcc 错误与 C++14 多态 lambda
- 是否可以找出多态C++ 14 lambda 的参数类型和返回类型
- 多态lambda的非类型模板参数
- 多态lambda的默认参数