본문으로 바로가기

C++14 에 자료형을 통한 튜플의 객체에 접근할 수 있게 되었습니다.


C++14 이전) 


1
2
3
4
5
6
7
std::tuple<stringintfloat> mytuple("ABC"510.2f);
 
std::string st = get<0>(mytuple);    // ABC
int i = get<1>(mytuple);    // 5
float f = get<2>(mytuple);    // 10.2f
 
std::tie(st, i, f) = mytuple;    // 또는 이렇게 한번에 
cs

C++14 추가됨)

1
2
3
4
5
std::tuple<stringintfloat> mytuple("ABC"510.2f);
 
std::string st = get<std::string>(mytuple);    // ABC
int i = get<int>(mytuple);    // 5
float f = get<float>(mytuple);    // 10.2f
cs

당연히 같은 타입이 존재한다면 이것은 에러입니다.

1
2
3
std::tuple<stringstringfloat> mytuple2("ABC""DEF"10.2f);
std::string st = get<std::string>(mytuple2);    //error, string 형이 2개여서 뭘 가져올지 모름
float f = get<float>(mytuple2);
cs

구조체의 래핑과 using 키워드를 통해 조금 더 직관적이게 만들 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
struct FirstName : std::string { using std::string::basic_string; };
struct LastName : std::string { using std::string::basic_string; };
 
void printAddress(const std::tuple<FirstName, LastName>& _add) {
    cout << std::get<FirstName>(_add) << "  " <<
        std::get<LastName>(_add) << endl;
}
int main() {
    auto add1 = std::make_tuple(FirstName("김"), LastName("덕배"));
    auto add2 = std::make_tuple(FirstName("박"), LastName("아무개"));
 
    printAddress(add1);    // 김  덕배
    printAddress(add2);    // 박  아무개
}
cs