lambda尾随返​​回类型auto的用法是什么? [英] What is the usage of lambda trailing return type auto?

查看:98
本文介绍了lambda尾随返​​回类型auto的用法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[]() -> auto { return 4; }中添加-> auto的用途是什么?

What is the usage of adding -> auto in []() -> auto { return 4; }?

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

推荐答案

默认情况下为auto.该标准 [expr.prim.lambda]/4 如下: :

It is auto by default. The Standard, [expr.prim.lambda]/4, reads:

如果 lambda-expression 不包含 lambda-declarator ,则好像 lambda-declarator (). lambda返回类型为auto,如果由[dcl.spec.auto]中所述的return语句提供和/或推导,则由 trailing-return-type 替换. >

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形成其他返回类型,即:-> auto&-> const auto&-> auto&&-> decltype(auto).适用返回类型扣除的标准规则.应当记住,auto永远不会推论为引用类型,因此默认情况下,lambda返回非引用类型.

So, -> auto itself is not useful. However, we can form other return types with auto, namely: -> auto&, -> const auto&, -> auto&&, -> decltype(auto). Standard rules of return type deduction apply. One should bear in mind that auto is never deduced to be a reference type, so by default a lambda returns a non-reference type.

一些(平凡的)例子:

// 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&的版本,并且简并的情况不值得倒退禁止."


PiotrNycz's addition. As pointed out in comments (credit to @StoryTeller) - the real usage is version with auto& and const auto& and "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 !

这篇关于lambda尾随返​​回类型auto的用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆