Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

c++ - Can the structured bindings syntax be used in polymorphic lambdas

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;
}

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;
});

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...