std::tie 创建左值引用的 tuple,或将 tuple 解包为独立对象

说明

std::tie : 创建左值引用的 tuple,或将 tuple 解包为独立对象
可以对std::tuple以及std::pair进行解包

返回值

含左值引用的 std::tuple 对象。

示例

void std_tie_test()
{
	using RetTuple = std::tuple<std::string, std::int32_t, std::pair<std::string, std::int32_t>>;
	auto func = []()->RetTuple{return { "string", 0, {"string_pair", 2} }; };

	std::string strRes;	std::string strPairRes;
	std::int32_t intRes; std::int32_t intPairRes;

	std::tie(strRes, intRes, std::tie(strPairRes, intPairRes)) = func();
	std::cout << strRes << "," << intRes << "," << strPairRes << "," << intPairRes << std::endl;

	std::map<int, string>mapItoS;

	bool insRes{ false };
	//std::ignore任何值均可赋给而无效果的未指定类型的对象。目的是令 std::tie 在解包 std::tuple 时作为不使用的参数的占位符使用。
	std::tie(std::ignore, insRes) = mapItoS.insert({ 1, "string" });

	if (insRes)
	{
		std::cout << "Insert value success!" << std::endl;
	}
}

输出结果:

string,0,string_pair,2
Insert value success!

std::ignore

C++源码

// STRUCT _Ignore
struct _Ignore { // struct that ignores assignments
    template <class _Ty>
    constexpr const _Ignore& operator=(const _Ty&) const noexcept /* strengthened */ {
        // do nothing
        return *this;
    }
};

_INLINE_VAR constexpr _Ignore ignore{};

其实就是通过重载=但里面什么也没有做,直接将传进来的值抛弃。利用了赋值操作运算符和模板,可以抛弃任意类型的值。

自己实现

namespace ISTD
{
	struct _Ignore 
	{
		template<typename T> 
		const _Ignore& operator=(const T& t) const
		{
			std::cout << "Using assigning operator" << std::endl;
			return *this;
		}
	};
	_Ignore ignore;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值