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 起)
(C++14 起为 constexpr) |
|
创建包含其参数的左值引用或 std::ignore 实例的元组。
目录 |
参数
| args | - | 用于构造元组的零个或多个左值参数。 |
返回值
一个包含左值引用的 std::tuple 对象。
可能的实现
template <typename... Args> constexpr // 自 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 { // 依次比较 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; // 解包 pair 对象: 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
时跳过元素的占位符
(常量) |