gpt4 book ai didi

c++ - 下一代 std::tie

转载 作者:太空宇宙 更新时间:2023-11-04 14:37:50 29 4
gpt4 key购买 nike

当一个函数需要返回两个参数时,你可以使用 std::pair 编写它:

std::pair<int, int> f()
{return std::make_pair(1,2);}

如果你想使用它,你可以这样写:

int one, two;
std::tie(one, two) = f();

这种方法的问题是您需要定义'one'和'two',然后将它们分配给f() 的返回值。如果我们能写出像这样的东西会更好

auto {one, two} = f();

我看过一个讲座(对不起,我不记得是哪一个了),演讲者说 C++ 标准的人们正在尝试做类似的事情。我认为这个讲座是2年前的。有谁知道现在(几乎在 c++17 中)您是否可以做到这一点或类似的事情?

最佳答案

是的,有一个东西叫structured bindings允许以这种方式初始化多个值。

语法使用square brackets然而:

#include <utility>

std::pair<int, int> f()
{
//return std::make_pair(1, 2); // also works, but more verbose
return { 1, 2 };
}

int main()
{
auto[one, two] = f();
}

demo

关于c++ - 下一代 std::tie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45984214/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com