본 게시글은 제가 에이콘 출판사의 "C++17 STL 프로그래밍" 서적을 학습하며 정리한 게시글입니다.
구조체 바인딩 (Structured Binding)
- C++17에서 추가된 문법
- 구조체나 pair, tuple로 묶은 요소들을 풀어서 각각의 변수에 할당할 수 있게 해주는 문법
#include <iostream>
#include <string>
#include <tuple>
#include <chrono>
using namespace std;
// 배당금과 제수 파라미터를 받으며, 분수 뿐 아니라 나머지 값도 반환하는 수학 함수
pair<int, int> divide_remainder(int devidend, int divisor)
{
return pair<int, int>(devidend, divisor);
}
tuple<string, chrono::system_clock::time_point, unsigned> stock_info(const string& name)
{
//...
}
int main()
{
// c++17에서 신택스 슈거와 자동화 타입 추론이 결합된 구조체 형태의 바인딩 추가됨
// pair나 tuple 또는 구조체로부터 개별 변수에 각각 할당할 수 있다 (다른 언어에서는 언패킹이라고 불린다)
// pair 예제
auto [fraction, remainder] = divide_remainder(16, 3);
// tuple 예제
auto [name, time, count] = stock_info("test");
std::cout << "16 / 3 is "
<< fraction << " with a remainder of "
<< remainder << '\n';
//----
// 구조체 바인딩 형태는 tuple과도 함께 동작한다
}
- 타입의 경우 auto로 받고, 대괄호를 열어서 변수 이름을 순서대로 넣어주면
- 그 변수들 안에 순서대로 차곡 차곡 멤버들이 들어간다
*구조체(struct)를 바인딩하는 경우, 아래와 같이 내부 모든 멤버들이 비정적 멤버들이여야 하고,
- 외부에서 접근 가능해야 한다.
#include <iostream>
using namespace std;
struct Test
{
int testInt;
float testFloat;
};
int main()
{
Test test{ 3, 3.14 };
auto [intMember, floatMember] = test;
}
구조체 바인딩 문법은 std::map을 순회할 때 특히 유용하다.
댓글