命名空间
变体
操作

std::tie

来自 cppreference.cn
< cpp‎ | utility‎ | tuple
 
 
 
 
定义于头文件 <tuple>
template< class... Types >
std::tuple<Types&...> tie( Types&... args ) noexcept;
(自 C++11 起)
(constexpr 自 C++14 起)

创建对其参数的左值引用或 std::ignore 实例的 tuple。

内容

[编辑] 参数

args - 零个或多个用于构造 tuple 的左值参数。

[编辑] 返回值

包含左值引用的 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 可以用于为结构体引入字典序比较或解包 tuple;
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 对象
(函数模板) [编辑]
创建 转发引用tuple
(函数模板) [编辑]
(C++11)
通过连接任意数量的 tuple 来创建 tuple
(函数模板) [编辑]
(C++11)
在使用 tie 解包 tuple 时跳过元素的占位符
(常量) [编辑]