Std::function and Std::bind function pointer __ function

Source: Internet
Author: User
Tags bind static class

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;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.