C++ 分配给std::tie和引用的元组之间有什么区别?

C++ 分配给std::tie和引用的元组之间有什么区别?,c++,reference,tuples,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 ); 评估结果为真 我还检查了是否是msvc的错误,但所有编译器都给出了相同的

我对以下元组业务感到有点困惑:

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 );
评估结果为真

我还检查了是否是msvc的错误,但所有编译器都给出了相同的结果。

函数实际上初始化了引用的
std::tuple
的成员,其中
std::tuple
不能由模板
std::tuple
初始化。操作
std::tie()
执行,初始化相应的对象如下所示:

std::tuple<int&, float&> test = 
    std::tuple<int&, float&>(testint, testfloat) = std::make_tuple(testint, testfloat);
std::元组测试=
std::tuple(testint,testfloat)=std::make_tuple(testint,testfloat);

(显然,您通常会使用与已绑定变量不同的值)。

问题在于rhs
std::make_tuple(testint,testfloat)
不返回引用数组,它返回
std::tuple
,这是一个临时变量,其值不能绑定到左值引用。如果需要引用的元组,可以使用helper函数:


这与
tie
之间的区别在于,引用在构造时由
std::tie(a,b)
初始化。

这两个
make\u tuple
tie
都将通过参数推断返回的类型。但是,
tie
将根据推导的类型生成左值引用类型,
make\u tuple
将生成实际的tuple

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

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


tie
的目标是创建一个临时元组,以避免绑定对象的临时副本,其不良影响是,如果条目对象是本地临时对象,则不能
返回
a
tie

我猜,因为它们是不同类型的,并且没有从一个到另一个的转换,但是有一个模板化的拷贝分配操作符,它可以在平局时工作

检查代码

#include <tuple>
#include <iostream>

int main() {

    std::tuple<int> a{};

    std::cout << std::get<0>(a) << std::endl;

    std::tuple<float> b{1.f}; //note float type

    a = b;

    std::cout << std::get<0>(a) << std::endl;

}
output: 0 1
#包括
#包括
int main(){
std::元组a{};

无法定义“不工作”,请发布完整的代码。我替换了“不工作”,但我认为代码已经足够完整了。缺少什么?如果不是左值引用,那么std::tie元组中的值是什么?std::make_元组生成临时值不是问题,在将std::make_对的结果存储在局部变量中,然后尝试将其分配给refere的元组时,可以观察到相同的行为nces或std::tie@Barabasstd::tie元组中的值是左值引用。它们分别由
a
b
初始化。我知道std::tie是左值引用的元组,但是与下一行的std::tuple有什么区别?啊,我想我明白了。std::tie(a,b)是一个包含两个对a和b的引用的元组,而std::tuple没有引用任何东西。这就是问题所在吗?@Barabas:是的,这是正确的。我考虑过不同的符号,最终解决了连接的赋值/初始化问题,主要是因为原始用户也试图进行初始化。
std::tuple<int&, float&> a = std::tie( testint, testfloat );

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

int main() {

    std::tuple<int> a{};

    std::cout << std::get<0>(a) << std::endl;

    std::tuple<float> b{1.f}; //note float type

    a = b;

    std::cout << std::get<0>(a) << std::endl;

}
output: 0 1