tuple_tie
tuple_tie (lvalue 참조 튜플 생성 함수)
std::tie는 전달받은 인자들에 대한 lvalue 참조들의 튜플을 생성해 주는 함수예요. 이 함수를 활용하면 여러 변수를 하나의 튜플로 묶어서 편리하게 다룰 수 있고, 튜플이나 페어의 값을 손쉽게 풀어낼 수도 있답니다. std::ignore와 함께 사용하면 특정 요소를 건너뛰는 것도 가능해요.
출처: cppreference
본문
std::tie는 <tuple> 헤더에 정의되어 있으며, C++11부터 사용할 수 있어요. C++14부터는 constexpr로 지정되어 컴파일 타임 상수 표현식에서도 활용할 수 있답니다.
<tuple> 헤더에 정의됨 |
||
|---|---|---|
template < class ... Types > std :: tuple < Types & ... > tie ( Types & ... args ) noexcept ; |
(C++11부터) (C++14부터 constexpr) |
매개변수
| args | - | 튜플을 구성할 0개 이상의 lvalue 인자예요. |
|---|
반환값
lvalue 참조들을 담고 있는 std::tuple 객체를 반환해요.
가능한 구현
template < typename ... Args > constexpr // since C++14 std :: tuple < Args & ... > tie ( Args & ... args ) noexcept { return { args ...}; }
참고 사항
std::tie는 std::pair를 풀어내는 데에도 사용할 수 있어요. std::tuple에는 페어로부터의 변환 할당이 정의되어 있기 때문이에요:
bool result;
std::tie(std::ignore, result) = set.insert(value);
예제
std::tie는 구조체에 사전식 비교를 도입하거나 튜플을 풀어내는 데 사용할 수 있어요. 2)std::tie는 구조적 바인딩과도 함께 동작한답니다:
#include <cassert>
#include <iostream>
#include <set>
#include <string>
#include <tuple>
struct S
{
int n;
std::string s;
float d;
friend bool operator<(const S& lhs, const S& rhs) noexcept
{
// compares lhs.n to rhs.n,
// then lhs.s to rhs.s,
// then lhs.d to rhs.d
// in that order, first non-equal result is returned
// or false if all elements are equal
return std::tie(lhs.n, lhs.s, lhs.d) < std::tie(rhs.n, rhs.s, rhs.d);
}
};
int main()
{
// Lexicographical comparison demo:
std::set<S> set_of_s;
S value{42, "Test", 3.14};
std::set<S>::iterator iter;
bool is_inserted;
// Unpack a pair:
std::tie(iter, is_inserted) = set_of_s.insert(value);
assert(is_inserted);
// std::tie and structured bindings:
auto position = [](int w) { return std::tuple(1 * w, 2 * w); };
auto [x, y] = position(1);
assert(x == 1 && y == 2);
std::tie(x, y) = position(2); // reuse x, y with tie
assert(x == 2 && y == 4);
// Implicit conversions are permitted:
std::tuple<char, short> coordinates(6, 9);
std::tie(x, y) = coordinates;
assert(x == 6 && y == 9);
// Skip an element:
std::string z;
std::tie(x, std::ignore, z) = std::tuple(1, 2.0, "Test");
assert(x == 1 && z == "Test");
}
같이 보기
| 구조적 바인딩 (C++17) | 초기화자의 하위 객체나 튜플 요소에 지정된 이름을 바인딩해요 [edit] |
|---|---|
| make_tuple (C++11) | 인자 타입들로 결정되는 타입의 튜플 객체를 생성해요 (함수 템플릿) [edit] |
| forward_as_tuple (C++11) | 전달 참조들의 튜플을 생성해요 (함수 템플릿) [edit] |
| tuple_cat (C++11) | 임의 개수의 튜플들을 연결하여 튜플을 생성해요 (함수 템플릿) [edit] |
| ignore (C++11) | tie로 튜플을 풀 때 요소를 건너뛰기 위한 자리표시자예요 (상수) [edit] |