c++ - C++ 中哪些地方实际需要尾随返回类型?

标签 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;
}

... 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 的类型。任何人都可以告诉我为什么编译器无法推断出函数的返回类型,以及除了模板之外是否还有任何其他用途我们必须使用尾随返回类型。

最佳答案

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

关于c++ - C++ 中哪些地方实际需要尾随返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62123767/

相关文章:

c++ - gdb - 列出当前函数的源而不输入其名称

c++ - 具有函数、输入和输出类型的可变参数模板

c++ - 给定迭代器检索容器的比较函数

c++ - 使用 lambda 构造 std::function 时 libstdc++ 和 libc++ 之间的不同行为

c++ - USS C++套接字编程和_OE_SOCKETS

c++ - 错误 LNK2019 : unresolved external symbol Visual Studio 2013 with openCV

C++ 错误 - 返回一个字符数组

c++ - Winpcap - pcap_next_ex 与 pcap_loop

c++ - 使用迭代器实现状态机(ala 生成器)

c++ - 为什么允许 int 和 const int 的不同转换函数?