C++11 std::function and std::bind

 std::function is a wrapper for callable objects, and its most important function is to implement delayed calls:

#include "stdafx.h"
#include<iostream>// std::cout
#include<functional>// std::function

void func(void)
{
    std::cout << __FUNCTION__ << std::endl;
}

class Foo
{
public:
    static int foo_func(int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};

class Bar
{
public:
    int operator() (int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};

intmain()
{
    // bind normal function
    std::function<void(void)> fr1 = func;
    fr1 ();

    // bind the static member function of the class
    std::function<int(int)> fr2 = Foo::foo_func;
    std::cout << fr2(100) << std::endl;

    // bind the functor
    Bar bar;
    fr2 = bar;
    std::cout << fr2(200) << std::endl;

    return 0;
}

 The above code defines std::function<int(int)> fr2, then fr2 can represent a type of function with the same return value and parameter table. It can be seen that fr2 saves the referred function, which can be called in the subsequent program process. This usage is very common in practical programming.

  std::bind is used to bind a callable with its arguments. After binding, it can be saved using std::function and called when we need it:

  (1) Bind the callable object and its parameters into a functor;

  (2) Some parameters can be bound.

  When binding partial arguments, use std::placeholders to determine which arguments the placeholders will be the first arguments the call will take.

#include "stdafx.h"
#include<iostream>// std::cout
#include<functional>// std::function

class A
{
public:
    int i_ = 0; // C++11 allows non-static data members to be initialized at their declaration (inside their owning class)

    void output(int x, int y)
    {
        std::cout << x << "" << y << std::endl;
    }

};

intmain()
{
    A a;
    // Bind member function, save as functor
    std::function<void(int, int)> fr = std::bind(&A::output, &a, std::placeholders::_1, std::placeholders::_2);
    // call member function
    fr(1, 2);

    // bind member variable
    std::function<int&(void)> fr2 = std::bind(&A::i_, &a);
    fr2() = 100;//Assign member variables
    std::cout << a.i_ << std::endl;


    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325662706&siteId=291194637