![](/img/trans.png)
[英]What does const means in auto return declaration with trailing return type?
[英]What is the usage of lambda trailing return type auto?
在[]() -> auto { return 4; }
中添加-> auto
什么用? []() -> auto { return 4; }
?
對我來說-與[]() { return 4; }
[]() { return 4; }
默認情況下是auto
的。 該標准[expr.prim.lambda] / 4的內容如下:
如果lambda表達式不包含lambda聲明符 ,則好像lambda聲明符為
()
。 lambda返回類型為auto
,如果提供了返回值 ,並且/或者根據[dcl.spec.auto]中的說明從return
語句推導得出,則將其替換為尾隨返回類型 。
我的加法。
因此, -> auto
本身沒有用。 但是,我們可以使用auto
來形成其他返回類型,即: -> auto&
, -> const auto&
, -> auto&&
, -> decltype(auto)
。 適用歸還類型扣除的標准規則 。 應該記住,永遠不會推導auto
為引用類型,因此默認情況下,lambda返回非引用類型。
一些(簡單的)示例:
// 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&
,“退化的情況根本不值得向后彎腰。”
看到:
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 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.