我有兴趣了解尾随auto&&返回类型的确切含义,特别是区别于decltype(auto),这在此处不起作用,以及未指定的返回类型,这也不起作用。
在下面的代码中,fn返回x_参数的字段。当参数是左值时,x_作为左值返回,等等。
在 的示例中,即使提供了左值参数fn_bad[123],它似乎也会返回。int我知道为什么-> auto会导致这种情况,但我希望-> decltype(auto)返回int&. 为什么只有-> auto&&工作?
#include <utility>
struct Foo { int x_; };
int main() {
auto fn_bad1 = [](auto&& foo) -> decltype(auto) { return std::forward<decltype(foo)>(foo).x_; };
auto fn_bad2 = [](auto&& foo) -> auto { return std::forward<decltype(foo)>(foo).x_; };
auto fn_bad3 = [](auto&& foo) { return std::forward<decltype(foo)>(foo).x_; };
auto fn = [](auto&& foo) -> auto&& { return std::forward<decltype(foo)>(foo).x_; };
Foo a{};
fn(a) = fn(Foo{100}); // doesn't compile with bad1, bad2, bad3
}