std:: tie
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::tuple
| Member functions | ||||
| Non-member functions | ||||
|
tie
|
||||
|
(until C++20)
(until C++20)
(until C++20)
(until C++20)
(until C++20)
(C++20)
|
||||
| Helper concepts | ||||
|
(C++23)
|
||||
| Helper classes | ||||
|
(C++23)
|
||||
|
(C++23)
|
||||
| Deduction guides (C++17) |
|
ヘッダーで定義
<tuple>
|
||
|
template
<
class
...
Types
>
std:: tuple < Types & ... > tie ( Types & ... args ) noexcept ; |
(C++11以降)
(constexprはC++14以降) |
|
引数への左辺値参照、または std::ignore のインスタンスからなるタプルを生成します。
目次 |
パラメータ
| args | - | タプルを構築するための0個以上の左辺値引数。 |
戻り値
lvalue参照を含む std::tuple オブジェクト。
実装例
template <typename... Args> constexpr // 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);
例
1)
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 { // lhs.nとrhs.nを比較し、 // 次にlhs.sとrhs.sを比較し、 // 次にlhs.dとrhs.dを比較 // その順序で、最初の非等価な結果が返される // または全ての要素が等しい場合はfalseが返される return std::tie(lhs.n, lhs.s, lhs.d) < std::tie(rhs.n, rhs.s, rhs.d); } }; int main() { // 辞書式比較のデモ: std::set<S> set_of_s; S value{42, "Test", 3.14}; std::set<S>::iterator iter; bool is_inserted; // ペアのアンパック: std::tie(iter, is_inserted) = set_of_s.insert(value); assert(is_inserted); // std::tieと構造化束縛: 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); // tieでx, yを再利用 assert(x == 2 && y == 4); // 暗黙的な変換が許可される: std::tuple<char, short> coordinates(6, 9); std::tie(x, y) = coordinates; assert(x == 6 && y == 9); // 要素のスキップ: std::string z; std::tie(x, std::ignore, z) = std::tuple(1, 2.0, "Test"); assert(x == 1 && z == "Test"); }
関連項目
| 構造化バインディング (C++17) | 指定された名前を初期化子の部分オブジェクトまたはタプルの要素にバインドする |
|
(C++11)
|
引数の型によって定義される型の
tuple
オブジェクトを作成する
(関数テンプレート) |
|
(C++11)
|
転送参照
の
tuple
を作成する
(関数テンプレート) |
|
(C++11)
|
任意の数のタプルを連結して
tuple
を作成する
(関数テンプレート) |
|
(C++11)
|
tie
を使用して
tuple
を展開する際に要素をスキップするためのプレースホルダ
(定数) |