Search code examples
c++c++11std-function

Is there any benefit of storing lambda function into std::function?


From https://en.cppreference.com/w/cpp/utility/functional/function

void print_num(int i)
{
    std::cout << i << '\n';
}
 
int main()
{
    // store a free function
    std::function<void(int)> f_display = print_num;
    f_display(-9);

    // store a lambda
    std::function<void()> f_display_42 = []() { print_num(42); };
    f_display_42();
}

What is the advantage of storing a lambda into a name than the previous approach ?


Solution

  • The advantage is that you don't need to know what is the type of the callable in order to store it. For instance, how do you declare an std::vector of things that can be called as a function? With std::function is easy:

    std::vector<std::function<void()>> handler_list;
    

    You can easily store in handler_list lambdas, explicit function objects or function pointers, without caring for their actual type. Another use is inside a class:

    class Something {
    public:
        void register_callback(std::function<void()> callback)
        {
            this->callback = callback;
        }
    
        //...
    
    private:
        std::function<void()> callback;
        //...
    };