对下面的元组业务有点疑惑:
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_tuple
和 tie
都会通过参数推断返回的类型。但是 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/