맨체스터 사는 개발자

[맨체스터개발자/Modern C++] Structed Binding 본문

개발/C++

[맨체스터개발자/Modern C++] Structed Binding

aaamy91 2021. 5. 20. 04:16

https://en.cppreference.com/w/cpp/language/structured_binding

Structed Binding 은 C++ 17에서 추가된 기능으로 쉽게 설명하자면 tuple이나 map 같은 자료구조를 auto와 대괄호를 사용해서 쉽게 접근 밑 가독성을 높일 수 있다.


아래 예를 보면 p 를 structed binding을 해서 x_coord, y_coord로 사용하고 있다.

Point p = { 1,2 };
      
// Structure binding
auto[ x_coord, y_coord ] = p;
      
cout << "X Coordinate : " << x_coord << endl;
cout << "Y Coordinate : " << y_coord << endl;


​지금 다니는 회사에서는 보통 map 구조를 iterate 할 때 사용한다.

이전 버전이라면, it.first, it.second 이런 형식으로 사용 했기 때문에 가독성이 떨어지지만, structed binding을 이용하면 가독성도 높이고 소스코드 길이도 짧아진다

std::map<std::wstring, std::wstring> FileList;
//이전 버전
for(std::map<std::wstring, std::wstring>::iterator it = FileList.begin(); it != FileList.end(); it++)
{
    openfile(it.first + it.second);
}


//C++17
for(auto& [path, filename] : FileList)
{
    openfile(path+filename);
}
​