【问题标题】:What is the usage of lambda trailing return type auto?lambda 尾随返回类型 auto 的用途是什么?
【发布时间】:2019-02-04 05:23:57
【问题描述】:

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

对我来说 - 它与 []() { return 4; } 没有什么不同

【问题讨论】:

    标签: c++ lambda c++14 language-lawyer trailing-return-type


    【解决方案1】:

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

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

    我的补充。

    所以,-> auto 本身没有用处。但是,我们可以用auto形成其他返回类型,即:-> auto&-> const auto&-> auto&&-> decltype(auto)。返回类型扣除的标准rules 适用。请记住,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 的补充。 正如 cmets 中所指出的(归功于 @StoryTeller) - 真正的用法是带有 auto&amp;const auto&amp; 的版本,并且“退化的情况不值得向后弯曲禁止。”

    见:

    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 !
    

    【讨论】:

    • 你知道吗 - 为什么对于 c++11 这段代码不能编译?您的回答表明这个默认值从一开始就在这里(lambda 是 C++11)。那是一些修复吗?
    • @PiotrNycz,C++11 中的函数没有 auto 返回类型。在 C++11 中你不能写 auto foo() { return 4; }。这是一个 C++14 特性。
    • @PiotrNycz - 请记住,C++14 规则允许 decltype(auto)auto&amp;&amp;auto const&amp; 等等。退化的情况是不值得向后弯曲来禁止的。
    • @StoryTeller 这很有意义!我看到-&gt; auto const&amp; 和其他人的用法。感谢您的指出。
    • @PiotrNycz、-&gt; decltype(auto)-&gt; auto&amp;&amp; 也很有用。例如,考虑一个采用 auto&amp;&amp; var 的 lambda。
    猜你喜欢
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 2023-03-04
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多