How can I store a lambda expression as a field of a class in C++11?

后端 未结 3 1638
余生分开走
余生分开走 2020-12-04 17:52

I\'d like to create a class where the client can store a lambda expression like []() -> void {} as a field of the class, but I can\'t figure out how to do so

3条回答
  •  心在旅途
    2020-12-04 18:21

    The only way I can think of to store a lambda in a class is to use a template with a helper make_ function:

    #include 
    #include 
    
    template
    class MyClass {
        Lambda _t;
    public:
        MyClass(Lambda &&t) : _t(std::forward(t)) {
            _t();
        }
    };
    
    template
    MyClass make_myclass(Lambda &&t) {
        return { std::forward(t) };
    }
    
    int main() {
        make_myclass([] {
            printf("hi");
        });
    }
    

提交回复
热议问题