0

Hi I came across this example

 auto [ptr, ec] { std::from_chars(str.data(), str.data() + str.size(), result) };

Can someone please explain the what is the syntax autp [ptr,ec] {} , this is something I am seeing for the first time. Is this new in C++ ?

Any link to the documentation will be very much appreciated.

Thanks

cpp_hex
  • 603
  • 1
  • 5
  • 7
  • 8
    It's called structured binding. Available since C++17: https://en.cppreference.com/w/cpp/language/structured_binding. – wohlstad Jun 23 '22 at 08:19
  • It is looking like definition of lambda function. https://en.cppreference.com/w/cpp/language/lambda Captures prt and ec variables and run code specified in { } – MihanEntalpo Jun 23 '22 at 08:23
  • 1
    @MihanEntalpo No, it's structured binding. It's lambda syntax only if it doesn't start with the `auto` keyword. – 康桓瑋 Jun 23 '22 at 08:24
  • `std::pair f(); auto p = f();` would be the classic way, `p` being the pair returned. Now with structured binding you could automatically unpack the pair as `auto [f, s] = f();` with `f` and `s` holding the `int`s of the pair's first and second member – note that I used assignment syntax here, which is equivalent, but makes (in my eyes) the code more obvious... – Aconcagua Jun 23 '22 at 08:26
  • Ok, I see no semicolon in braces, so it couldn't be a lambda. – MihanEntalpo Jun 23 '22 at 08:29
  • Hm... This drives me to add two rules for my personal coding conventions: 1. For structured bindings assignment syntax (see my comment above) gets *mandatory*. 2. For lambdas the optional `()` for empty argument list gets mandatory as well (i.e. `auto f = [](){ /*... */}`. -> Above pseudo-ambiguities (admitted, just requires a closer look...) solved. – Aconcagua Jun 23 '22 at 08:38

0 Answers0