我们可以用一个c ++ 1y std :: tie()类函数做深关系吗? [英] can we do deep tie with a c++1y std::tie() -like function?

查看:142
本文介绍了我们可以用一个c ++ 1y std :: tie()类函数做深关系吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以在c ++ 11 / 1y中编写一个 std :: tie 的变体,它深深地融入了一个元组。也就是说, tie((x,y),z)= make_tuple(make_tuple(1,2),3)绑定 y,z 1,2和3 ,如以下示例所示。这将是很好。感谢。

Is there a way to write a variant of std::tie in c++11/1y that ties deeply into a tuple. That is, one in which tie((x,y),z) = make_tuple(make_tuple(1,2),3) binds x, y, z to 1, 2 and 3, respectively as in the following example. It would be nice. Thanks.

#include <tuple>
#include <iostream>
using namespace std;

int main() {
  int x, y ,z;
  auto t = make_tuple(1,2);
  std::tie(y,x)= t;
  //std::tie((x,y),z) = make_tuple(t,3); //not working
  cout << x << y << z << endl;
  return 0;
}


推荐答案

std :: tuple_cat

std::tie(x,y,z) = std::tuple_cat(t, make_tuple(3)); 

您可以将 tuples 元组,以避免处理嵌套元组。我认为使嵌套元组变平的解决方案会更复杂。

You can string together tuples as one long tuple, to avoid dealing with nested tuples. I think the solution to flattening nested tuples would be more complex.

只是为了澄清 std :: tie 工作(我想)。 std :: tie 从其参数构造一个包含左值引用的元组。使用赋值运算符时,将执行复制分配 std :: tie((x,y),z)不会做你想的。您将(x,y)赋给逗号运算符,其中x被丢弃。没有魔法继续,其中嵌套由括号确定。如果 std :: tie 的参数之一是元组,那么相应的参数也应该是元组。即: std :: tie(tuple,3)= std :: make_tuple(std :: make_tuple(1,2),3)。但是这不是你想要的,这是我的建议来自于,因为它似乎不是你的意图是扁平嵌套的元组。

Just to make a clarification on how std::tie works (I think). std::tie constructs a tuple of lvalue references from its arguments. When you use the assignment operator, copy assignments are performed. std::tie((x,y),z) doesn't do what you think. You're subjecting (x,y) to the comma operator, where x is discarded. There is no magic going on, where nesting is determined by parentheses. If one of the arguments to std::tie is a tuple, then the corresponding argument should be a tuple as well. i.e.: std::tie(tuple, 3) = std::make_tuple(std::make_tuple(1, 2), 3). However this is not what you want, which is where my suggestion comes from, because it doesn't seem like your intention is to flatten a nested tuple.

这篇关于我们可以用一个c ++ 1y std :: tie()类函数做深关系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆