boost库使用—函数回调

boost库使用—函数回调


result_of

确定表达式的类型


包含头文件:

#include <boost/utility/result_of.hpp>

using namespace boost;


案例:

#include <iostream>
#include <boost/utility/result_of.hpp>
using namespace std;

int main()
{
	typedef double(*Func)(double);
	Func func = sqrt;
	result_of<Func(double)>::type x = func(5.0);
	cout << "type:"<<typeid(x).name() << endl;
	

	system("pause");
	return 0;
}

ref 和 cref

boost.ref 应用代理模式,引入对象包装器的概念;函数对象作为参数时使用较多;降低了复制的代价


包含头文件:

#include <boost/ref.hpp>

using namespace boost;


原型:

ref:  boost::reference_wrapper<T> ref(T& t);
cref: boost::reference_wrapper<T> ref(T const& t);

ref 用于包装按引用传递的值。
cref 用于包装按const引用传递的值。


#include <iostream>
#include <boost/ref.hpp>

using namespace std;

void test(int &n)
{
	n = n + 10;
	cout << "n:"<<n << endl;//20
}

int main()
{
	int n = 10;
	test(ref(n));
	cout << "n:" << n << endl;//20
	system("pause");
	return 0;
}

bind + function

关于两种说明在微信公众号:CPP后台服务器开发 中有,欢迎参观


bind + function + ref

案例:

#include <iostream>
#include "boost/bind.hpp"
#include "boost/ref.hpp"
#include <boost/function.hpp>

struct A
{
	A(int aValue) : m_value(aValue)
	{
		std::cout << "A()" << std::endl;
		m_value = 10;
	}

	A(const A& a)
	{
		std::cout << "A(const A&)" << std::endl;
		this->m_value = a.m_value;
	}

	int m_value;
};

void f(A a)
{
	std::cout << "f(A)" << std::endl;
}

void g(A& a)
{
	std::cout << "g(A&)" << std::endl;
}

void test(int x,int y)
{
	std::cout << "x:" << x << std::endl;
	std::cout << "y:"<< y << std::endl;
}
typedef boost::function<void(void)>Func;
typedef boost::function<void(int)>Func2;
int main()
{
	A a(10);

	std::cout << "...f1..." << std::endl;
	boost::bind(&f, a)();
	std::cout << "...f2..." << std::endl;
	boost::bind(&f, boost::ref(a))();

	std::cout << "...g1..." << std::endl;
	boost::bind(&g, a)();
	std::cout << "...g2..." << std::endl;
	boost::bind(&g, boost::ref(a))();
	Func F(boost::bind(&g, boost::ref(a)));
	F();
	int x = 2,y =5;
	Func F2(boost::bind(&test, boost::ref(x), boost::ref(y)));
	F2();
	system("pause");
	return 0;
}

想了解学习更多C++后台服务器方面的知识,请关注:
微信公众号:C++后台服务器开发


发布了197 篇原创文章 · 获赞 68 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/Travelerwz/article/details/103756148