【问题标题】:Is there something that limits the future C++ standard from introducing multiple return values?有没有什么东西限制了未来的 C++ 标准引入多个返回值?
【发布时间】:2020-02-04 22:36:55
【问题描述】:

在较新版本的 C++ 标准中,我们可以编写具有多个返回值的函数,例如

std::tuple<int, std::string, float> someFunction0();

这迫使我们将函数称为

int a;
std::string last_name;
float f_par;
std::tie(a, last_name, f_par) = someFunction0();

我的问题是,有什么东西阻止 C++ 委员会引入“更简单”的多返回值语法形式吗?比如

[int, std::string, float] someFunction1();

这将允许您在调用函数时声明更多内联

[int a, std::string last_name, float f_par] = someFunction1();

(可能有比我提供的更好的语法解决方案。)

在编译器方面,这应该不是问题,对吧?

【问题讨论】:

  • 如果我理解正确,我想你在问什么already exists
  • 啊,老鼠们,看来我的功课还没做呢!感谢您的回答!
  • 很少见的情况是您需要一个函数来返回多个值,但这些值的集合本身并没有足够的意义,不值得拥有一个命名的结构类型。并且即使返回值组本质上是没有意义的,使用结构体意味着你至少可以给出返回值names,这使得接收端清楚mean。想想map::insert 的代码有多可怕,因为pair.second 的含义莫名其妙。

标签: c++ standards multiple-return-values


【解决方案1】:

在您的示例中,std::tuple&lt;int, std::string, float&gt; someFunction0(); 仍然返回 一个 tuple 对象,由多个子对象组成。

是否有什么东西阻止了 C++ 委员会引入“更简单”的多返回值语法形式?

您可以使用 C++17 structured binding declaration 对其进行解包/解构:

案例 2:绑定类似元组的类型

float x{};
char  y{};
int   z{};

std::tuple<float&,char&&,int> tpl(x,std::move(y),z);
const auto& [a,b,c] = tpl;
// a names a structured binding that refers to x; decltype(a) is float&
// b names a structured binding that refers to y; decltype(b) is char&&
// c names a structured binding that refers to the 3rd element of tpl; decltype(c) is co`

【讨论】:

    猜你喜欢
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多