Lambda closure type constructors

后端 未结 1 1893
借酒劲吻你
借酒劲吻你 2021-02-08 19:06

The cppreference shows that there are different rules for lambda closure type constructors.

Default Construction - Until C++14

Cl

1条回答
  •  灰色年华
    2021-02-08 20:04

    There was a shortcoming. We couldn't use lambdas quite as "on the fly" as one might have wanted. C++20 (with the addition of allowing lambdas in unevaluated contexts) makes this code valid:

    struct foo {
        int x, y;
    };
    
    std::map m;
    

    Note how we defined the compare function inline? No need to create a named functor (could be a good idea otherwise, but we aren't forced too). And there's no need to break the declaration in two:

    // C++17
    auto cmp = [](foo const& a, foo const& b) { return a.x < a.y; };
    std::map m(cmp); // And also need to pass and hold it!
    

    Usages like this (and many more) were the motivating factor in making this change. In the example above, the anonymous functors type will bring all the benefits a named functor type can bring. Default initialization and EBO among them.

    0 讨论(0)
提交回复
热议问题