function template classes and bind template functions that use them to implement functions similar to function pointers, but are more flexible than function pointers, especially when functions point to non-static member functions of a class.
Std::function can bind to global functions/class static member functions (class static member functions are no different from global functions), and you need to use Std::bind if you want to bind to non-static member functions of a class.
#include <iostream>
#include <functional>
using namespace std;
typedef std::function<void () > fp;
void G_fun ()
{
cout<< "g_fun ()" <<endl;
}
Class A
{public
:
static void A_fun_static ()
{
cout<< "a_fun_static ()" <<endl;
}
void A_fun ()
{
cout<< "a_fun ()" <<endl;
}
void A_fun_int (int i)
{
cout<< "a_fun_int ()" <<i<<endl;
}
Non-static class members, because they contain the this pointer, need to use bind
void init ()
{
fp fp1=std::bind (&a::a_fun,this);
FP1 ();
}
void Init2 ()
{
typedef std::function<void (int) > FPI;
For parameters to use placeholder std::p laceholders::_1
FPI f=std::bind (&a::a_fun_int,this,std::p laceholders::_1);
F (5);
}
;
int main ()
{
//bind to global function
fp F2=FP (&g_fun);
F2 ();
Bind to class static member function
FP F1=FP (&a::a_fun_static);
F1 ();
A (). Init ();
A (). Init2 ();
return 0;
}
At the same time, Std::bind is bound to a virtual function to show polymorphic behavior.
#include <iostream>
#include <functional>
using namespace std;
typedef std::function<void () > fp;
Class A
{public
:
virtual void F ()
{
cout<< "a::f ()" <<endl;
}
void init ()
{
//std::bind can display the polymorphic behavior of
FP f=std::bind (&a::f,this);
f ();
}
;
Class B:public A
{public
:
virtual void F ()
{
cout<< "b::f ()" <<endl;
}
};
int main ()
{a
* pa=new B;
Pa->init ();
return 0;
}