说明
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;
}