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

Is there a use case for std::function that is not covered by function pointers, or is it just syntactic sugar?


The notation for std::function is quite nice when compared to function pointers. However, other than that, I can't find a use case where it couldn't be replaced by pointers. So is it just syntactic sugar for function pointers?


Solution

  • std::function<> gives you the possibility of encapsulating any type of callable object, which is something function pointers cannot do (although it is true that non-capturing lambdas can be converted to function pointers).

    To give you an idea of the kind of flexibility it allows you to achieve:

    #include <functional>
    #include <iostream>
    #include <vector>
    
    // A functor... (could even have state!)
    struct X
    {
        void operator () () { std::cout << "Functor!" << std::endl; }
    };
    
    // A regular function...
    void bar()
    {
        std::cout << "Function" << std::endl;
    }
    
    // A regular function with one argument that will be bound...
    void foo(int x)
    {
        std::cout << "Bound Function " << x << "!" << std::endl;
    }
    
    int main()
    {
        // Heterogenous collection of callable objects
        std::vector<std::function<void()>> functions;
    
        // Fill in the container...
        functions.push_back(X());
        functions.push_back(bar);
        functions.push_back(std::bind(foo, 42));
    
        // And a add a lambda defined in-place as well...
        functions.push_back([] () { std::cout << "Lambda!" << std::endl; });
    
        // Now call them all!
        for (auto& f : functions)
        {
            f(); // Same interface for all kinds of callable object...
        }
    }
    

    As usual, see a live example here. Among other things, this allows you to realize the Command Pattern.