如何在C++中初始化返回元组的变量?

我有一个函数 xyz() 返回一个tuple<std::string, double>. 当我单独调用此函数时,我可以执行以下操作:

auto [tresh, loss] = xyz(i);

这不会导致任何错误,但是如果我想在 if else 块中使用 xyz() 函数,那么我不能在以下代码中再使用treshandloss变量。例子:

if (boolX) {
        auto [tresh, loss] = xyz(i);
    } else {
        auto [tresh, loss] = xyz(j);
    }
std::cout << tresh << std::endl;

我还尝试在 if else 块之前初始化 tresh 和 loss 变量并删除auto,但这会产生以下错误:

Expected body of lambda expression

如何解决这个问题?

回答

根据确切的代码,您可以替换为三元

auto [tresh, loss] = boolX ? xyz(a) : xyz(b);
std::cout << tresh << std::endl;

  • Or even `auto [tresh, loss] = xyz(boolX ? a : b);`.

回答

在创建结构化绑定之前,std::tie是解包元组的解决方案。

std::string tresh;
double loss;
if (boolX) {
    std::tie(tresh, loss) = xyz(i);
} else {
    std::tie(tresh, loss) = xyz(i);
}
std::cout << tresh << std::endl;

它被认为是笨重的,因为您必须在初始化之前声明变量,但这正是您在这里想要的。

  • [`std::ignore`](https://en.cppreference.com/w/cpp/utility/tuple/ignore) can even be used: `std::tie(tresh, std::ignore) = xyz(i);`
  • *"but that's exactly what you want here"* - More like "that's what you settle for here".

回答

您可以使用 lambda 表达式:

auto [tresh, loss] = [&boolX, &i, &j](){
    if (boolX) {
        return xyz(i);
    } else {
        return xyz(j);
    }
}();
std::cout << tresh << std::endl;

  • @MarekR It's your opinion. I wouldn't define a function for this and you will find this style in different companies.

以上是如何在C++中初始化返回元组的变量?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>