C++中哪里实际需要尾随返回类型?
Where trailing return type is actually needed in C++?
我正在阅读有关尾随返回类型的信息。我遇到了这个网站 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的类型。任何人都可以让我知道为什么编译器无法推断函数的返回类型,以及是否有任何其他用途,我们必须使用模板以外的尾随返回类型。
它知道大写的类型Lhs
和Rhs
,但不知道小写变量lhs
和rhs
。它们是在decltype
之后声明的。
相关文章:
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 为什么返回类型中需要typename?C++
- C++中哪里实际需要尾随返回类型?
- 如果函数是在类的主体中定义的,我是否需要在成员函数的返回类型中指定 typename?
- 为什么函数的返回类型与实际句子不一致?
- 为什么在.h中定义的私有结构需要.cpp文件中的返回类型中的范围
- C++14 'auto'能够获取函数返回类型,我们还需要 std::result_of<> 吗?
- 为什么编译器需要在已经类限定的成员函数定义的返回类型上使用类限定符
- 为什么在返回兼容类型时需要显式std::move
- 使用函子的返回类型来声明模板方法的返回类型,不需要decltype
- c++调用约定是否受标准约束,因为在声明fn时不需要定义函数的返回类型
- 需要解决的限制:抽象类不能用于返回类型
- 需要为虚函数的模板返回类型
- 以下返回类型的实际含义是什么
- 为什么C++赋值运算符需要返回类型
- 哪个编译器是正确的? 'template'在需要模板化返回类型之前?