在 C++ 中实际需要尾随返回类型的地方?

kad*_*ina 2 c++ c++11

我正在阅读有关尾随返回类型的信息。我遇到了这个网站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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Joh*_*ica 5

它知道大写类型LhsRhs,但不知道小写变量lhsrhs。它们在decltype.