std::tie
From cppreference.com
| ヘッダ <tuple> で定義 |
||
template< class... Types > std::tuple<Types&...> tie( Types&... args ) noexcept; |
(C++11以降) (C++14以降constexpr) |
|
引数への左辺値参照、または std::ignore のインスタンスのタプルを作成します。
目次 |
[編集] パラメータ
| args | - | タプルを構築するための0個以上の左辺値引数。 |
[編集] 戻り値
左辺値参照を含む std::tuple オブジェクト。
[編集] 可能な実装
template <typename... Args> constexpr // since C++14 std::tuple<Args&...> tie(Args&... args) noexcept { return {args...}; } |
[編集] 注釈
std::tie は、std::pair から std::tuple への変換代入演算子があるため、std::pair をアンパックするために使用できます。
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 { // 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) | 指定された名前を初期化子のサブオブジェクトまたはタプル要素に束縛します |
| (C++11) |
引数型によって定義された型の tuple オブジェクトを生成する(関数テンプレート) |
| (C++11) |
転送参照の tuple を生成する(関数テンプレート) |
| (C++11) |
任意の数のタプルを連結して tuple を生成する(関数テンプレート) |
| (C++11) |
tie を使用してタプルをアンパックする際に要素をスキップするためのプレースホルダ。(定数) |