Feb 9, 2022

[C++] structure binding with auto&&

Reference:
https://devblogs.microsoft.com/oldnewthing/20201014-00/?p=104367

auto&& is universal reference thus collapse &&& to & with binding to l-value.


#include <iostream>
#include <string>
using namespace std;

struct Customer {
  string a;
  string b;
  int c;
};

int main() {
  Customer c{"Tim", "Starr", 42};
  auto [f, l, v] = c;

  std::cout << "f/l/v: " << f << ' ' << l << ' ' << v << '\n';

  // modify structured bindings via references:
  // auto&& is universal reference; thus for l-value it collapse from
  // &&& to &; auto = Customer&
  auto &&[f2, l2, v2] = c; 
  
  // auto&& is universal reference; here binds to r-value; auto = Customer
  auto &&[f2, l2, v2] = Customer{"a", "b", 42}; 

  cout << f2 << endl;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.