What is the difference between assigning to std::tie and tuple of references?(分配给 std::tie 和引用元组有什么区别?)
问题描述
对下面的元组业务有点疑惑:
I am a bit puzzled by the following tuple business:
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 它可以工作,但是直接分配给引用元组不会编译,给出
With std::tie it works, but assigning directly to the tuple of references doesn't compile, giving
错误:从‘std::tuple
"error: conversion from ‘std::tuple<int, float>’ to non-scalar type ‘std::tuple<int&, float&>’ requested"
或
"没有合适的用户定义的从 std::tuple
"no suitable user-defined conversion from std::tuple<int, float> to std::tuple<int&, float&>"
为什么?我仔细检查了编译器是否真的与通过执行此操作分配给的类型相同:
Why? I double checked with the compiler if it's really the same type that is being assigned to by doing this:
static_assert( std::is_same<decltype( std::tie( testint, testfloat ) ), std::tuple<int&, float&>>::value, "??" );
评估结果为真.
我还检查了 online 是否可能是 msvc 的错误,但所有编译器给出的结果都是一样的.
I also checked online to see if it maybe was the fault of msvc, but all compilers give the same result.
推荐答案
std::tie()函数实际上是初始化std::tuplestd::tuple<T&...> 不能由临时 std::tuplestd::tie() 所做的操作和初始化相应对象的表达式如下:
The std::tie() function actually initializes the members of the std::tuple<T&...> of references where is the std::tuple<T&...> can't be initialized by a templatory std::tuple<T...>. The operation std::tie() does and initializing a corresponding object would be expressed like this:
std::tuple<int&, float&> test =
std::tuple<int&, float&>(testint, testfloat) = std::make_tuple(testint, testfloat);
(显然,您通常会使用与已绑定变量不同的值).
(obviously, you would normally use different values than those of the already bound variables).
这篇关于分配给 std::tie 和引用元组有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:分配给 std::tie 和引用元组有什么区别?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
