What does it mean to inherit from lambda?

前端 未结 3 1367
清酒与你
清酒与你 2020-12-23 08:56

Found this code which looks to be interesting:

auto a = [](){};

class B : decltype(a)
{
};

I want to know what it does. Can this be useful

3条回答
  •  [愿得一人]
    2020-12-23 09:42

    Lambdas are function objects underneath, with additional syntatic sugar. a evaluates to something like that (with the MyLambda name being a random name, just like when you make namespace {} - namespace name will be random):

    class MyLambda {
    public:
        void operator()() {
        }
    }
    

    So when you inherit from a lambda, what you're doing is inheriting from an anonymous class / structure.

    As for usefulness, well, it's as useful as any other inheritance. You can have the functionality of multiple lambdas with multiple inheritance in one object, you can add new methods to it to extend it. I can't think of any real application at the moment, but I'm sure there are many.

    Refer to this question for more information.

提交回复
热议问题