名稱空間
變體
操作

std::tie

來自 cppreference.com
< cpp‎ | 工具庫‎ | 元組
 
 
 
 
定義於標頭檔案 <tuple>
template< class... Types >
std::tuple<Types&...> tie( Types&... args ) noexcept;
(C++11 起)
(C++14 起為 constexpr)

建立一個由其引數的左值引用或 std::ignore 例項組成的元組。

目錄

[編輯] 引數

args - 零個或多個用於構造元組的左值引數。

[編輯] 返回值

一個包含左值引用的 std::tuple 物件。

[編輯] 可能的實現

template <typename... Args>
constexpr // since C++14
std::tuple<Args&...> tie(Args&... args) noexcept
{
    return {args...};
}

[編輯] 注意

std::tie 可以用於解包 std::pair,因為 std::tuple 具有從 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) 將指定名稱繫結到初始化器的子物件或元組元素[編輯]
建立一個由引數型別定義的 tuple 物件
(函式模板) [編輯]
建立一個轉發引用tuple
(函式模板) [編輯]
(C++11)
透過連線任意數量的 tuple 建立一個 tuple
(函式模板) [編輯]
(C++11)
在使用 tie 解包 tuple 時跳過元素的佔位符
(常量) [編輯]