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

后端 未结 3 1641
余生分开走
余生分开走 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 17:57

    In case of void () simple function pointer can be used (declaration syntax is void (*pointer_name) ();). Lambda with empty capture block is implicitly convertible to function pointer with same signature. And std::function have runtime and size (std::function is at least three times larger) overhead.

    struct S
    {
      void (*f_p)() {}; // `{}` means `= nullptr`;
    };
    
    int main()
    {
        S s { [] { std::cout << "Lambda called\n"; }};
    
        s.f_p();
    
        S s2;
        if (s2.f_p) // check for null
            s.f_p();
    
        s2.f_p = [] { std::cout << "Lambda2 called\n"; };
        s2.f_p();
    
        s2.f_p = std::terminate; // you can use regular functions too
    
        s2.f_p();
    }
    

    Output

    Lambda called
    Lambda2 called
    terminate called without an active exception
    

提交回复
热议问题