我正在阅读有关尾随返回类型的内容。我偶然发现了这个网站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; }
... Since the compiler parses the source code from left to right, it sees lhs and rhs before their definitions, and rejects the code. By using the trailing return type, we can circumvent this limitation.
但根据我的理解,当编译器到达 decltype(lhs + rhs) 时,它应该已经知道 lhs 和 rhs 的类型。任何人都可以告诉我为什么编译器无法推断出函数的返回类型,以及除了模板之外是否还有任何其他用途我们必须使用尾随返回类型。
最佳答案
它知道大写类型Lhs
和Rhs
,但不知道小写变量lhs
和rhs
。它们在 decltype
之后声明。
关于c++ - C++ 中哪些地方实际需要尾随返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62123767/