c++ std::function和std::bind

时间:2022-05-22 09:39:18
#include "iostream"
#include <functional>  
#include <stdarg.h>
using namespace std;

class Root
{
private:
	typedef std::function<int(int)> print_func;
	print_func F_print;

public:
	void setPrint(print_func fun)
	{
		F_print = fun;
		F_print(10);
	}

	int pritf(int i)
	{
		cout << i << endl;
		return 0;
	}

};

#define CALLBACK_0(__selector__,__target__,...) bind(__selector__,__target__,##__VA_ARGS__)
#define CALLBACK_1(__selector__,__target__,...) bind(__selector__,__target__,std::placeholders::_1,##__VA_ARGS__)

int demo(char *msg, ...)
{
	va_list argp;
	int argno = 0;
	int para;
	va_start(argp, msg);
	while (true)
	{
		para = va_arg(argp, int);
		if (para == 0) break;
		printf("Parameter #%d is : %d\n", argno, para);
		argno++;
	}
	va_end(argp);
	return 0;
}

void main()
{

	Root * root = new Root();
	root->setPrint(CALLBACK_1(&Root::pritf, root));

	delete root;
	root = nullptr;

	demo("",1,2,3,4,5,6,7,8,9);

	system("pause");
}