网站首页 > 基础教程 正文
td::tuple 是 C++ 标准库中的一个模板类,C++11引入, 它用于创建一个固定大小的异质容器,其中可以存储不同类型的对象。std::tuple 提供了一种方便的方式来组合不同类型的对象到一个单一的实体中,而无需创建一个新的结构体或类。std::tuple 通常用于函数返回多个值,或者作为一种通用的容器来存储不同类型的数据。
1. 介绍
1.1 定义
template <class... _Types>
class tuple;
1.2 成员函数
(构造函数) | 构造新的 tuple (公开成员函数) |
operator= | 赋值一个 tuple 的内容给另一个 (公开成员函数) |
swap | 交换两个 tuple 的内容 (公开成员函数) |
1.3 非成员函数
make_tuple(C++11) | 创建一个 tuple 对象,其类型根据各实参类型定义 (函数模板) |
tie(C++11) | 创建左值引用的 tuple,或将 tuple 解包为独立对象 (函数模板) |
forward_as_tuple(C++11) | 创建转发引用的 tuple (函数模板) |
tuple_cat(C++11) | 通过连接任意数量的元组来创建一个tuple (函数模板) |
std::get(std::tuple)(C++11) | 元组式访问指定的元素 (函数模板) |
operator== | 按字典顺序比较 tuple 中的值 (函数模板) |
operator<=> (C++20) | 按字典顺序比较 tuple 中的值 (函数模板) |
std::swap(std::tuple)(C++11) | 特化 std::swap 算法 (函数模板) |
1.3 辅助类
std::tuple_size(C++11) | 在编译时获得 tuple 的大小 (类模板特化) |
std::tuple_element(C++11) | 获得指定元素的类型 (类模板特化) |
std::uses_allocator(C++11) | 特化 std::uses_allocator 类型特征 (类模板特化) |
std::basic_common_reference(C++23) | 确定二个 tuple 的共同引用类型 (类模板特化) |
std::common_type(C++23) | 确定二个 tuple 的共同类型 (类模板特化) |
ignore(C++11) | 用 tie 解包 tuple 时用来跳过元素的占位符 (常量) |
2. 示例
2.1 创建
#include<iostream>
#include <utility>
int main() {
class A {
int val = 0;
public:
A(int x) : val(x) {
std::cout << "A(int x) : " << val <<std::endl;
}
A(std::string str, int x) : val(x) {
std::cout << "A(std::string str, int x) : " << val << std::endl;
}
};
//直接初始化
{
std::tuple<int, std::string> x(1, "1234");
std::tuple<A, std::string> y(1, "1234");
}
//std::make_tuple
{
auto x = std::make_tuple<int, std::string>(1, "123");
auto y = std::make_tuple(A(2), "string", 0.1f);
auto z = std::make_tuple(std::string(""), A("", 3), 2);
std::tuple<A, float> h = std::make_tuple(4, 9);
}
//创建空的元组然后赋值
{
//std::tuple<A, std::string, int> x;
//错误,这里会调用A、std::string、int的默认构造函数,
//而A没有定义默认构造函数。
//可以对A添加默认构造函数:
//A(){} 或 A(int x = 0)
std::tuple<std::string, int> x;
std::get<0>(x) = "hello";
std::get<1>(x) = 999;
//std::tuple<std::string, int> x();
//这也是错误的, 它会调用创建一个空的tuple
//推测是实例化了
// template <> class tuple<> { // empty tuple
}
//std::tuple_cat
{
auto x = std::make_tuple(1, 0.3);
std::tuple<std::string, A> y("hello", 20);
auto z = std::tuple_cat(x, y);
//z元素个数
std::cout << std::tuple_size<decltype(z)>::value << std::endl;
std::cout << std::tuple_size_v<decltype(z)> << std::endl;
}
//other
{
A a(10);
std::string b("hello");
auto x = std::make_tuple(std::ref(a), std::ref(b));
auto y = std::tie(a, b);
//注意里面的元素只是引用而已, 随a、b改变
b = "world";
std::cout << "x: " << std::get<1>(x) << std::endl;
std::cout << "tie: " << std::get<1>(y) << std::endl;
//std::forward_as_tuple
auto func = [](std::tuple<A, std::string>&& tt) {
std::cout <<"lambda: " << std::get<1>(tt) << std::endl;
};
func(std::forward_as_tuple(a, b));
//operator=
auto z = x;
}
return 0;
}
2.2 函数
#include<iostream>
#include <utility>
int main() {
//打印输出
auto printf_tuple = [](const char* str,
std::tuple<int, std::string, double>& x) {
std::cout << str << " : 0=" << std::get<0>(x);
std::cout <<" 1=" << std::get<1>(x);
std::cout << " 2=" << std::get<2>(x) << std::endl;
};
//operator= operator==
auto t = std::make_tuple(10, std::string("hello"), 0.3);
std::tuple<int, std::string, double> t2(10, "hello", 0.3);
auto t3(t2);
auto t4 = t2;
if (t == t2 && t == t4) {
std::cout << "same" << std::endl;
}
//std::tuple_size
int size = std::tuple_size<decltype(t)>();
std::cout << size << std::endl;
//std::get
for (int i = 0; i < size; i++) {
//std::get<i>(t);
//错误,编译时期展开,所以i要常量
}
std::cout << "0=" << std::get<0>(t);
std::cout << " 1=" << std::get<1>(t);
std::cout << " 2=" << std::get<2>(t) << std::endl;
//swap std::swap
std::get<0>(t4) = 100;
std::get<1>(t4) = "world";
std::get<2>(t4) = 0.9;
t4.swap(t2);
printf_tuple("t2", t2);
printf_tuple("t4", t4);
std::swap(t2, t4);
printf_tuple("t2", t2);
printf_tuple("t4", t4);
//std::tie 创建
int x = 10;
std::string y("std::tie");
double z = 0.3;
auto t5 = std::tie(x, y, z);
//t5 = std::tuple<int&, std::string&, double&>
//std::tie 解包
//std::ignore
std::tie(x, std::ignore, z) = t;
std::cout << "x=" << x;
std::cout << " z=" << z<<std::endl;
//std::tuple_element
std::tuple_element<0, std::tuple<bool, int>>::type v1 = false;
std::tuple_element<0, std::tuple<bool, int>>::type v2 = 100;
return 0;
}
2.3 场景
高级场景还是应用于模板元编程,不讨论。
普通场景就是减少结构体或类的应用:
- 返回值 与 参数
#include<iostream>
#include <utility>
std::tuple<bool, int, std::string> Ret1() {
return std::make_tuple(true, 10, std::string("Ret1"));
}
decltype(auto) Ret2() {
return std::make_tuple(true, 10, std::string("Ret1"));
}
auto Ret3(std::tuple<bool, int, std::string>&& arg) {
return arg;
}
std::tuple<bool, int, std::string>&& Ret4(std::tuple<bool, int, std::string>&& arg) {
return std::forward<std::tuple<bool, int, std::string>>(arg);
}
int main() {
auto r1 = Ret1();
auto r2 = Ret2();
if (r1 == r2) {
std::cout << "r1=r2 same" << std::endl;
}
auto r3 = Ret3(std::move(r2));
auto&& r4 = Ret4(std::move(r3));
//相当于
//std::tuple<bool, int, std::string>&& r4 = std::move(r3);
auto r5 = Ret4(std::move(r4));
return 0;
}
- 与容器结合
#include<iostream>
#include <utility>
#include <vector>
#include <map>
int main() {
using TUPLE = std::tuple<int, double, std::string>;
//vector
std::vector<TUPLE> vec{ {1, 0.1, "str0.1"}, {2, 0.2, "str0.2"} };
vec.emplace_back(3, 0.3, "str0.3");
vec.push_back(std::make_tuple(4, 0.4, std::string("str0.4")));
for (auto& elem : vec) {
std::cout << "0=" << std::get<0>(elem);
std::cout << " 1=" << std::get<1>(elem);
std::cout << " 2=" << std::get<2>(elem) << std::endl;
}
//map
std::map<int, TUPLE> map({ {1, {1, 0.1, "str0.1"}}, {2, {2, 0.2, "str0.2"}} });
map.insert({ { 3, {3,0.3,"str0.3"} }, { 4, {4,0.4,"str0.4"} } });
map.emplace(5, std::make_tuple(5, 0.5, std::string("str0.5")));
std::cout << "\n\n" << std::endl;
for (auto& elem : map) {
std::cout << "0=" << std::get<0>(elem.second);
std::cout << " 1=" << std::get<1>(elem.second);
std::cout << " 2=" << std::get<2>(elem.second) << std::endl;
}
return 0;
}
- 与智能指针结合
#include<iostream>
#include <utility>
#include <list>
#include <memory>
int main() {
using TUPLE = std::tuple<int, double, std::string>;
//被指针包含
std::shared_ptr<TUPLE> x(new TUPLE(1, 0.1, "1111"));
x = std::make_shared<TUPLE>(2, 0.2, "2222");
//tuple包含指针
using TUPLE_01 = std::tuple<int, std::shared_ptr<std::string>>;
TUPLE_01 a;
{
TUPLE_01 b(100, std::make_shared<std::string>("hi"));
a = b;
}
std::cout << std::get<1>(a)->c_str() << std::endl;
//list and std::shared_ptr
std::list<std::shared_ptr<TUPLE>> lst;
std::shared_ptr<TUPLE> ptr(new std::tuple(1, 0.1, std::string("str0.1")));
lst.emplace_back(ptr);
lst.push_back(std::make_shared<TUPLE>(2, 0.2, "str0.2"));
lst.insert(lst.end(), std::make_shared<TUPLE>(3, 0.3, "str0.3"));
for (auto& elem : lst) {
std::cout << "0=" << std::get<0>(*elem.get());
std::cout << " 1=" << std::get<1>(*elem.get());
std::cout << " 2=" << std::get<2>(*elem.get()) << std::endl;
}
return 0;
}
- 与函数调用
#include <iostream>
#include <utility>
template <typename Func, typename Tuple>
auto apply_impl(Func&& f, Tuple&& t){
return std::apply(std::forward<Func>(f), std::forward<Tuple>(t));
}
template <typename Func, typename... Args>
auto perfect_forward_apply(Func&& f, Args&&... args){
return apply_impl(std::forward<Func>(f), \
std::forward_as_tuple(std::forward<Args>(args)...));
}
void test_01(int a, double b) {
std::cout << "test_01(" << a \
<< "," << b << ")" << std::endl;
}
int main()
{
int a = 42;
double b = 3.14;
perfect_forward_apply(test_01, a, b);
std::apply(test_01, std::forward_as_tuple(a, b));
auto lamdba_01 = [](int x, const char* y) {
std::cout << "lamdba_01(" << x << ", " << y << ")\n";
return x * 2;
};
perfect_forward_apply(lamdba_01, 100, "hello world!");
std::apply(lamdba_01, std::forward_as_tuple(100, "hello world"));
std::invoke(lamdba_01, 100, "hello world!");
return 0;
}
小言解析:
这段C++代码主要展示了如何使用std::apply、std::forward_as_tuple以及自定义的perfect_forward_apply函数来调用函数或lambda表达式,并将参数完美转发给它们。
首先,代码定义了两个模板函数:apply_impl和perfect_forward_apply。
- apply_impl函数接收一个函数f和一个元组t,然后使用std::apply来调用函数f并将元组t中的元素作为参数传递给f。std::apply是一个函数模板,它接受一个可调用对象和一个元组,并使用元组中的元素作为参数来调用该对象。
- perfect_forward_apply函数则是一个便利函数,它接收一个函数f和一系列参数args,然后使用std::forward_as_tuple将这些参数打包成一个元组,并调用apply_impl来应用这个函数和元组。std::forward_as_tuple是一个函数模板,它生成一个元组,并将参数完美转发给元组。
test_01函数是一个简单的函数,它接受一个int和一个double作为参数,并将它们打印到标准输出。
在main函数中,代码首先创建了两个变量a和b,然后使用perfect_forward_apply和std::apply来调用test_01函数,并将a和b作为参数传递给它。
接下来,代码定义了一个lambda表达式lamdba_01,它接受一个int和一个const char*作为参数,并将它们打印到标准输出,然后返回x的两倍。然后,代码再次使用perfect_forward_apply、std::apply和std::invoke来调用这个lambda表达式,并传递相应的参数。
注意,这里使用了std::forward来完美转发参数。完美转发意味着保持参数的原始类型(例如,lvalue或rvalue)和值类别(例如,const或非const)不变地传递给函数或lambda表达式。这对于避免不必要的拷贝和保持代码的通用性非常重要。
最后,main函数返回0,表示程序正常结束。
3. 源码探索
实现比较有意思, 类似于套娃。
参考标准文档std::tuple - cppreference.com
就不展开解析了, 参见这篇文章
<C++中VS2019下STL的std::tuple元组深入剖析>https://zhuanlan.zhihu.com/p/397720700
猜你喜欢
- 2024-11-11 Linux下的C++ socket编程实例 linux c++ tcp
- 2024-11-11 C++11原子变量:线程安全、无锁操作的实例解析
- 2024-11-11 C++11的thread_local原理和应用范例
- 2024-11-11 知识重构-c++ : Lambda 知识重构拼音
- 2024-11-11 c++ 疑难杂症(4) std:vector c++ vector subscript out of range
- 2024-11-11 深入探索C++异步编程的奥秘 c++11异步编程
- 2024-11-11 C++ 开发中使用协程需要注意的问题
- 2024-11-11 golang极速嵌入式Linux应用开发(四)-协程与并发
- 2024-11-11 在计算机编程中,线程是指一个程序内部的执行流程
- 2024-11-11 C++ std:decay、std:bind、std:packaged_task 在模版编程的实践
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)