lambda trailing return type auto 的用法是什么?

What is the usage of lambda trailing return type auto?

[]() -> auto { return 4; }中加入-> auto有什么用?

对我来说 - 它与 []() { return 4; }

没有什么不同

默认为auto。标准 [expr.prim.lambda]/4 内容如下:

If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were (). The lambda return type is auto, which is replaced by the trailing-return-type if provided and/or deduced from return statements as described in [dcl.spec.auto].

我的补充。

所以,-> auto本身是没有用的。但是,我们可以用auto组成其他return类型,即:-> auto&-> const auto&-> auto&&-> decltype(auto)。 return 类型扣除的标准 rules 适用。应该记住 auto 永远不会被推断为引用类型,因此默认情况下 lambda return 是非引用类型。

几个(琐碎的)例子:

// 1.
int foo(int);
int& foo(char);

int x;

auto lambda1 = [](auto& x) { return x; };
static_assert(std::is_same_v<decltype(lambda1(x)), int>);

auto lambda2 = [](auto& x) -> auto& { return x; };
static_assert(std::is_same_v<decltype(lambda2(x)), int&>);

// 2.
auto lambda3 = [](auto x) { return foo(x); };
static_assert(std::is_same_v<decltype(lambda3(1)), int>);
static_assert(std::is_same_v<decltype(lambda3('a')), int>);

auto lambda4 = [](auto x) -> decltype(auto) { return foo(x); };
static_assert(std::is_same_v<decltype(lambda4(1)), int>);
static_assert(std::is_same_v<decltype(lambda4('a')), int&>);

// 3.
auto lambda5 = [](auto&& x) -> auto&& { return std::forward<decltype(x)>(x); };
static_assert(std::is_same_v<decltype(lambda5(x)), int&>);
static_assert(std::is_same_v<decltype(lambda5(foo(1))), int&&>);
static_assert(std::is_same_v<decltype(lambda5(foo('a'))), int&>);

PiotrNycz 的补充。 正如评论中所指出的(归功于@StoryTeller)——真正的用法是 auto&const auto& 和 "The degenerate case is just not something worth bending backwards to disallow."

参见:

int p = 7;
auto p_cr = [&]()  -> const auto& { return p; };
auto p_r = [&]()  -> auto& { return p; };
auto p_v = [&]()  { return p; }; 

const auto& p_cr1 = p_v(); // const ref to copy of p
const auto& p_cr2 = p_cr(); // const ref to p
p_r() = 9; // we change p here

std::cout << p_cr1 << "!=" << p_cr2 << "!\n";
// print 7 != 9 !