gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:43:09 24 4
gpt4 key购买 nike

我正在阅读有关尾随返回类型的内容。我偶然发现了这个网站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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com