std::function for callbacks in C++

std::function can be used in place of function pointers which is much simpler to use.

Following sample code explains how std::function can be used in various places.

#include <iostream>
#include <functional>


using namespace std;

void function1(int val) {
    cout << "Value input: " << val << endl;
}

static void function2(int val) {
    cout << "Value input: " << val << endl;
}

void pass_function_as_param(std::function<void(int)> fcn) {
    fcn(1000);
}

class cls1 {
    public:
        void member_fun(int val) {
            cout << "Member function called with input:" << val << endl;
        }
       
        void static_member_fun(int val) {
            cout << "Member function called with input:" << val << endl;
        }
};

class functor_cls {
    public:
        void operator()(int val) const
        {
            std::cout << "Value input: " << val << endl;
        }
};

int main()
{
    function<void(int)> fun;

    fun = function1; // assign
    fun(100);
   
    pass_function_as_param(fun);
   
    fun = function2; // re-assign to static function
    fun(200);

    // assigning functor to function
    fun = functor_cls();
    fun(300);

    // point to member function
    function<void(cls1&, int)> member_fun;
    member_fun = &cls1::member_fun;
   
    cls1 instance;
    member_fun(instance, 400);

    return 0;
}


/*********** OUTPUT **********

Value input: 100
Value input: 1000
Value input: 200
Value input: 300
Member function called with input:400


*/

No comments:

Post a Comment