std::tie
来自cppreference.com
| 在标头 <tuple> 定义
|
||
| (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::make_tuple(1, 2.0, "Test");
assert(x == 1 && z.compare("Test") == 0);
// 跳过一个元素:
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 时用来跳过元素的占位符 (常量) |