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

Source: Internet
Author: User
Tags bind static class

The function template class and the Bind template function, which can be used to implement functions like function pointers, are more flexible than function pointers, especially when a function is pointing to a non-static member function of a class.

Std::function can be bound to global function/class static member functions (class static member functions are not different from global functions), and if you want to bind to non-static member functions of a class, you need to use Std::bind.

#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 member, because it contains the this pointer, you 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, use the 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 exhibit 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 exhibit polymorphic behavior in
		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;
}


Related Article

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.