可以在多态lambda中使用结构化绑定语法吗 [英] Can the structured bindings syntax be used in polymorphic lambdas

查看:92
本文介绍了可以在多态lambda中使用结构化绑定语法吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结构化绑定使遍历具有如下范围的for循环的地图的迭代更加清晰易读

Structured bindings make it more clean and readable to iterate through a map with a range based for loop like below

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

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

But can structured bindings be used in lambda expressions like the following?

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

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

From what it looks like the above code does not work with the online C++ compiler I found here https://wandbox.org/permlink/sS6r7JZTB3G3hr78.

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

If it does not work then is there a good reason the above is not supported? Or is it just something that has not been proposed yet? The template will only be instantiated on use, so the structured bindings' "unbinding" process can occur where the instantiation is requested (i.e. when the function is called)

推荐答案

该语法当前不允许使用;结构化绑定是 简单声明 :

This is not currently allowed by the syntax; structured bindings are a simple-declaration:

简单声明:[...]
- attribute-specifier-seq opt decl-specifier-seq ref-qualifier opt [ 标识符列表 ] 初始化器 ;

simple-declaration:[...]
- attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ] initializer ;

,而函数参数由 参数引入-declaration-list ,其中包含 声明符 s:

while function parameters are introduced by a parameter-declaration-list, which contains declarators:

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

The declarators specify the names of these entities and (optionally) modify the type of the specifiers with operators such as * (pointer to) and () (function returning).

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

That is, a structured binding is a (block-level) statement syntax - you can see this by noting that the grammar for it ends in a semicolon ;. Allowing structured bindings in a lambda parameter list would require additional grammar to be added.

这听起来像是个好主意,但我无法立即看到语法上的歧义;肯定值得讨论,因为它比替代方案更好,更简洁地解决了您提出的用例.

It sounds like a good idea, and I can't immediately see any ambiguity in the syntax; it would certainly be worth discussing as it solves your presented use case nicely and more concisely than the alternatives.

这篇关于可以在多态lambda中使用结构化绑定语法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆