C++中哪里实际需要尾随返回类型?

Where trailing return type is actually needed in C++?

本文关键字:返回类型 实际需要 C++      更新时间:2023-10-16

我正在阅读有关尾随返回类型的信息。我遇到了这个网站 https://blog.petrzemek.net/2017/01/17/pros-and-cons-of-alternative-function-syntax-in-cpp/它解释了这些返回类型的需求,并在下面提到。

template<typename Lhs, typename Rhs>
decltype(lhs + rhs) add(const Lhs& lhs, const Rhs& rhs) {
// error: ^^^ 'lhs' and 'rhs' were not declared in this scope
return lhs + rhs;
}

。由于编译器从左到右解析源代码,因此它会在定义之前看到 lhs 和 rhs,并拒绝代码。通过使用尾随返回类型,我们可以绕过此限制。

但根据我的理解,当编译器达到decltype(lhs + rhs(时,它应该已经知道lhs和rhs的类型。任何人都可以让我知道为什么编译器无法推断函数的返回类型,以及是否有任何其他用途,我们必须使用模板以外的尾随返回类型。

它知道大写的类型LhsRhs,但不知道小写变量lhsrhs。它们是在decltype之后声明的。