c++ - 分配给 std::tie 和引用元组有什么区别?

标签 c++ reference tuples

对下面的元组业务有点疑惑:

int testint = 1;
float testfloat = .1f;
std::tie( testint, testfloat ) = std::make_tuple( testint, testfloat );
std::tuple<int&, float&> test = std::make_tuple( testint, testfloat );

使用 std::tie 它可以工作,但是直接分配给引用元组不会编译,给出

"error: conversion from ‘std::tuple<int, float>’ to non-scalar type ‘std::tuple<int&, float&>’ requested"

"no suitable user-defined conversion from std::tuple<int, float> to std::tuple<int&, float&>"

为什么?我仔细检查了编译器是否真的与通过执行此操作分配给的类型相同:

static_assert( std::is_same<decltype( std::tie( testint, testfloat ) ), std::tuple<int&, float&>>::value, "??" );

评估结果为真。

我还检查了 online看看是不是msvc的问题,但是所有编译器给出的结果都是一样的。

最佳答案

make_tupletie 都会通过参数推断返回的类型。但是 tie 会根据推导的类型生成一个左值引用类型,而 make_tuple 会生成一个实际的元组。

std::tuple<int&, float&> a = std::tie( testint, testfloat );

std::tuple<int , float > b = std::make_tuple( testint, testfloat );

 

tie 的目的是制作一个临时元组来避免临时复制被捆绑的对象,不好的效果是,你不能 return 一个 tie 如果入口对象是本地临时对象。

关于c++ - 分配给 std::tie 和引用元组有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19800303/

相关文章:

c++ - 运行 WinForm 的函数 "In Background"(VS2010 c++)

reference - WiX 属性引用另一个属性

python - 对在 python 中将列表项分配给 vars 感到困惑

python - 键是 Python 中的一对整数的字典

haskell - 元组列表的类型构造函数是什么?

c++ - GCC 内联汇编错误 : block assembly operand not recognized

c++ - 如何将 std::unique_ptr 传递给函数

c# - 如何将函数参数列表转换为元组

c++ - 继承:包含派生类实例的基类模板容器

c++ - 在 C++ 中延长临时值的生命周期