C++ 是否有一行程序可以将元组/对解压到引用中?

C++ 是否有一行程序可以将元组/对解压到引用中?,c++,C++,我经常写这样的片段 int x,y,z; tie(x,y,z) = g[19]; 其中,例如,g是先前声明的 vector<tuple<int,int,int>> g(100); 有时甚至更糟,例如,如果访问是一个更复杂的表达式 tuple<int,int,int> &p = g[19]; // if the rhs was actually more complicated int &x = get<0>(p); int &a

我经常写这样的片段

int x,y,z; tie(x,y,z) = g[19];
其中,例如,
g
是先前声明的

vector<tuple<int,int,int>> g(100);
有时甚至更糟,例如,如果访问是一个更复杂的表达式

tuple<int,int,int> &p = g[19]; // if the rhs was actually more complicated
int &x = get<0>(p);
int &y = get<1>(p);
int &z = get<2>(p);
tuple&p=g[19];//如果rhs真的更复杂
int&x=get(p);
int&y=get(p);
int&z=get(p);
是否有更好的重构,更多的是分配给tie(…)的样式


据我所知,困难在于引用坚持要初始化。因此,在其他的词中,有可能使用C++中的代码> Tys<代码>语法来进行多变量初始化(这也会使早期的非引用用法更干净)?< /P> < P>可以编写一个结构来存储引用:

struct vector3d
{
    vector3d(std::tuple<int, int, int>& tuple)
      : x(std::get<0>(tuple)),
        y(std::get<1>(tuple)),
        z(std::get<2>(tuple))
    {}

    int& x;
    int& y;
    int& z;
};

您可以使用一个函数将其自动化,这样您就不必键入3行(或更多行):

模板
decltype(自动)从指定的(std::index\u序列、元组和元组)绑定
{
返回std::tuple{std::get(tuple)…};
}
模板
decltype(自动)tie_from(元组和元组)
{
从指定的_返回tie_(std::make_index_sequence{},tuple);
}
用途如下:

int x{ 2 };
std::tuple<int, int&, int> g19( 1, x, 3 );

// new tuple: ref to get<0>( g19 ), value of get<1>( g19 ), ref to get<2>( g19 )
auto t0{ tie_from<int&, int, int&>( g19 ) };

// new tuple: ref to get<0>( g19 ), ref to get<2>( g19 )
auto t1{ tie_from_specified<int&, int&>( std::index_sequence<0, 2>{}, g19 ) };
intx{2};
std::元组g19(1,x,3);
//新元组:ref to get(g19)、get值(g19)、ref to get(g19)
自动t0{tie_from(g19)};
//新元组:ref to get(g19),ref to get(g19)
自动t1{tie_from_specified(std::index_sequence{},g19)};

幸运的是,C++17正好有一个解决这个问题的方法,即。甚至可以改进非参考接口

auto[x, y, z] = g[i];
上面的行声明了x、y、z,并用
g[i]
的值初始化它们。它不仅更干净,而且对于构造成本较高的类型,它可能更有效

要获取对
g[i]
成员的引用,可以编写

auto& [x, y, z] = g[i];

有趣,但我想现在是时候定义一个命名结构来替换元组了……有趣的是,你应该问,有一个建议是C++17允许像
auto[x,y,z]=g()这样的语法这正是你想要的。有这样一篇文章:(不知道是否有更新的版本存在)足够公平。但是,将元组重构为命名结构既为全局名称空间添加了一个名称(除非我们玩更多的游戏,这会让意图变得不那么清晰,而不是更多),又消除了元组的其他便利,例如最新版本的默认操作符<.@Hiura:。包含措辞。考虑到当前标准,这似乎是目前最好的解决方案。我们将看到C++17的未来。你能提供一个如何使用结构化绑定声明的示例吗?@StevenVascellaro我写的两行代码(在修复了使用括号而不是括号的错误之后)是如何使用结构化绑定声明从
std::tuple
中获取值或引用的示例。我链接到的页面也有3个例子,有全面的解释。我想不出比这更好的例子了。在我的回答中有什么特别让你感到困惑吗?x、y和z需要分别声明和赋值吗?@StevenVascellaro他们不需要。这就是该功能的全部要点。它们在一行中声明和初始化。例如,在第一个示例中,
x
已声明,并从
g[i]
的第一个元素复制构造。因此,如果我想初始化一组整数,我是否会执行类似于
int num[3]={1,2,3};自动[x,y,z]=num
int x{ 2 };
std::tuple<int, int&, int> g19( 1, x, 3 );

// new tuple: ref to get<0>( g19 ), value of get<1>( g19 ), ref to get<2>( g19 )
auto t0{ tie_from<int&, int, int&>( g19 ) };

// new tuple: ref to get<0>( g19 ), ref to get<2>( g19 )
auto t1{ tie_from_specified<int&, int&>( std::index_sequence<0, 2>{}, g19 ) };
auto[x, y, z] = g[i];
auto& [x, y, z] = g[i];