元组tuple

一、元组tuple

递归继承和模板的特化组合实现
1、源码展示与分析

#include <tuple>
template<class _Ty>
	struct _Tuple_val			//成员类型
	{
	constexpr _Tuple_val()
		: _Val()
		{	// default construct
		}
		//此处设省略多行代码
	_Ty _Val;
	};
	
template<class... _Types>
	class tuple;
template<>class tuple<>	//全特化版本
	{
	//此处设省略多行代码
	};				// empty tuple
template<class _This,class... _Rest>	//特化版本
	class tuple<_This, _Rest...>
		: private tuple<_Rest...>		// 私有递归继承自Tuple<Tail...>
	{	// 递归元组定义
	//此处设省略多行代码
public:
	typedef _This _This_type;
	typedef tuple<_Rest...> _Mybase;	//定义基类类型
	_Tuple_val<_This> _Myfirst;			// 存储的元素
	};

2、其他成员函数

void swap(tuple& _Right)		//交换语义
_Mybase& _Get_rest() noexcept	//获取除第一个剩余元素的元组的引用
constexpr const _Mybase& _Get_rest() const noexcept	//const重载
constexpr bool _Equals(const tuple<_Other...>& _Right) const		//判断对应的每个元素是否相等
constexpr bool _Less(const tuple<_Other...>& _Right) const		//判断对应的每个元素否大于*this
std::tuple<> tp;		//全特化版本	构造函数
std::tuple<int, char, double, std::string> tp1;		//默认值完成构造
std::tuple<int, char, double, std::string> tp2(1, '@', 520.830, "Hello World!");				//构造函数
int i = 1; std::string str = "Hello World!";
std::tuple<int&, std::string> tp2(i, str);		//元素不一定为一般类型,还可以是类对象,引用指针等		构造函数

3、非成员函数

auto i2 = std::get<0>(tp2);		//获取单个元素的方式,但索引值不能动态传递,否则将发生编译错误
size_t size = std::tuple_size<decltype(tp2)>::value;	//获取元组的大小
std::tuple_element<1, decltype(tp2)>::type strtype;		//获取某个元素的类型,可以用typedef,using
strtype = "Hi";
tp1 = std::make_tuple(1, '@', 520.830, "Hello World!");	//和make_pair类似的创建方式
forward_as_tuple(_Types&&... _Args) 		//tuple的专属完美专递

二、pair键值对源码展示与分析(与元组tuple相似)

template<class _Ty1,class _Ty2>
	struct pair
	{	// store a pair of values
	using first_type = _Ty1;
	using second_type = _Ty2;
	template<class... _Types1,
		class... _Types2> inline
		pair(piecewise_construct_t,
			tuple<_Types1...> _Val1,
			tuple<_Types2...> _Val2);
	_Ty1 first;		// the first stored value
	_Ty2 second;	// the second stored value
	};

推荐相关文章Variadic Templates:https://editor.csdn.net/md/?articleId=118230016

如有错误或不足欢迎评论指出!创作不易,转载请注明出处。如有帮助,记得点赞关注哦(⊙o⊙)
更多内容请关注个人博客:https://blog.csdn.net/qq_43148810

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大胡子的艾娃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值