【发布时间】:2017-04-04 05:32:55
【问题描述】:
我只是在阅读a bit about tuples。
现在我不清楚以下语法:
std::tie (myint, std::ignore, mychar) = mytuple;
不难理解它的作用,但是从语言的角度来看会发生什么?我们以某种方式分配函数的返回值?
【问题讨论】:
我只是在阅读a bit about tuples。
现在我不清楚以下语法:
std::tie (myint, std::ignore, mychar) = mytuple;
不难理解它的作用,但是从语言的角度来看会发生什么?我们以某种方式分配函数的返回值?
【问题讨论】:
但是从语言的角度来看会发生什么?我们以某种方式分配函数的返回值?
是的,这可能是有效的,具体取决于函数的返回类型。有效的方式主要有两种:第一,函数可以返回一个对象的左值引用。
int i;
int &f() { return i; }
int main() { f() = 1; } // okay, assigns to i
其次,函数可以返回带有= 运算符实现的用户定义类型,可以在右值上调用:
struct S { void operator=(int) { } };
S f() { return {}; }
int main() { f() = 1; } // okay, calls S::operator=
后者是std::tie 的情况。
【讨论】:
structs 和 classes,在 C++11 中出现对 *this 的右值引用之前,即使是临时的,也可以始终分配给它! operator= 会起作用,即使结果被丢弃。这里有趣的部分是分配给tie 做了一些有用的。
std::tie(myint, std::ignore, mychar)的返回类型是std::tuple<int&, decltype((std::ignore)), char&>,其中int&是对myint的引用,char&是对mychar的引用。
当mytuple 分配给这个返回的元组引用时,mytuple 中的每个值都分配给存储在返回元组中的相应引用。这具有更新 myint 和 mychar 的效果。
std::tie(myint, std::ignore, mychar) // <-- expression
std::tuple<int&, decltype((std::ignore)), char&> // <-- type
std::tie(myint, std::ignore, mychar) = mytuple;
std::tuple<int&, decltype((std::ignore)), char&> = std::tuple<int, T, char>&;
// functions as
std::tuple<int , T , char >&
// ↓↓ = = = ↓↓
std::tuple<int&, decltype((std::ignore)), char&>
// end result:
myint = std::get<0>(mytuple);
mychar = std::get<2>(mytuple);
int& = int&;
char& = char&;
【讨论】:
decltype(std::ignore)&(或decltype((std::ignore)))。 .
tie 返回一个引用元组。您正在分配给该元组,这意味着元组成员分配(std::ignored 字段除外)。因为该元组的元素实际上是引用,所以您要分配给绑定的元素。
【讨论】:
来自 cpp 引用“创建一个左值引用的元组对其参数或 std::ignore 实例。”
从这个意义上说,它与你分配给运算符 [] 的返回值时并没有什么不同
vec[3]=5;
我们只需要提到 C++17 具有结构化绑定 auto [a,b,c] = 和 std::ignore with structured bindings?
【讨论】:
rvalue,对吧? (这在 C++ 中是不被禁止的)