Can the 'type' of a lambda expression be expressed?

后端 未结 4 488
小鲜肉
小鲜肉 2020-12-01 04:59

Thinking of lambda expressions as \'syntactic sugar\' for callable objects, can the unnamed underlying type be expressed?

An example:

struct gt {         


        
4条回答
  •  春和景丽
    2020-12-01 05:34

    No, you cannot put it into decltype because

    A lambda-expression shall not appear in an unevaluated operand

    You can do the following though

    auto n = [](int l, int r) { return l > r; };
    std::set s(n);
    

    But that is really ugly. Note that each lambda expression creates a new unique type. If afterwards you do the following somewhere else, t has a different type than s

    auto n = [](int l, int r) { return l > r; };
    std::set t(n);
    

    You can use std::function here, but note that this will incur a tiny bit of runtime cost because it needs an indirect call to the lambda function object call operator. It's probably negligible here, but may be significant if you want to pass function objects this way to std::sort for example.

    std::set> s([](int l, int r) { return l > r; });
    

    As always, first code then profile :)

提交回复
热议问题