21

Why I cannot use C++17 structured binding in this case?

std::map<int, int> m;
std::find_if( m.cbegin(), m.cend(), []( const auto & [x, y] ){ return x == y; } );
cigien
  • 57,834
  • 11
  • 73
  • 112
Kill KRT
  • 1,101
  • 2
  • 17
  • 37
  • Does this answer your question? [Can the structured bindings syntax be used in polymorphic lambdas](https://stackoverflow.com/questions/45541334/can-the-structured-bindings-syntax-be-used-in-polymorphic-lambdas) – cigien Jun 02 '21 at 21:55

1 Answers1

16

Structured binding works only with initializers. You need to have a particular object which you can bind to. Your lambda makes closure which will be called with different instances of pair of map. The place when you can use structured bindings is inside lambda body - you have a pair which you can refer to.

std::find_if( m.cbegin(), m.cend(), []( const auto & p ){ 
    const auto& [x,y] = p;
    return x == y; 
}); 
rafix07
  • 20,001
  • 3
  • 20
  • 33
  • 9
    Re: "Structured binding works only with initializers" - the thing is, that function arguments exactly designate *initialization context*. So it seems that structured binding *could* in theory be used there. (Subject to further language evolution, in case someone suggests that, of course.) – Mike Kaganski Oct 23 '21 at 08:17