Search code examples
c++functioncomparatorfunctor

Function which takes function/lambda/class with overloaded() as argument


I need write a function which can take another function/lambda/class with () operator overloaded as a parametr and correctly work with them (like 3th arg of std::sort. What it looks like in terms of C++ syntax?


Solution

  • You can make it a function template (like std::sort) with a template parameter that you assume is callable:

    template<typename Func>
    void myFunction(Func f)
    {
        f();
    }
    

    Now let's test it:

    void normalFunction()
    {
        std::cout << "Normal function.\n";
    }
    
    struct Functor {
        void operator()()
        {
            std::cout << "Functor object.\n";
        }
    };
    
    int main()
    {
        Functor functor;
    
        myFunction(normalFunction);
        myFunction(functor);
        myFunction([]{ std::cout << "Lambda.\n"; });
    }
    

    This will print:

    Normal function.
    Functor object.
    Lambda.