Can the structured bindings syntax be used in polymorphic lambdas

Viewed 4705

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)

2 Answers

I think this would be a great proposal (if isn't there one already) that would simplify code for algorithms that pass zip iterators/tuples of references. (for example https://github.com/correaa/iterator-zipper)

At the same time is seems that it is not something that you couldn't achieve using a bit more verbose code by extracting the structure in the first line of the function:

#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

(which strengthens the point that this is implementable and simple to add to the language).

A more streamlined version could be indented as:

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