#include <iostream> // std::cout
#include <boost/function.hpp> // boost::function
#include <boost/bind.hpp> // boost::bind
// 类AA
class CFAA
{
public:
// 测试虚函数的替代
void methodAA()
{
std::cout << "CFAA methodA() " << std::endl;
}
// 测试boost::function<void()> 附加参数
void methodArgInt(int num)
{
std::cout << "CFAA methodint() num=" << num << std::endl;
}
};
// 类BB
class CFBB
{
public:
// 测试虚函数的替代
void methodB()
{
std::cout << "CFBB methodB() " << std::endl;
}
// 测试boost::function作为函数参数
void methodArgBind(boost::function<void()> func, int num)
{
std::cout << "CFBB methodbind() num=" << num << std::endl;
func();
}
// 测试由methodArgBind填充func参数
void methodArgBind(boost::function<void(int)> func)
{
std::cout << "use from CFBB::methodArgBind(boost::function<void(int)> func)" << std::endl;
func(100);
}
};
int main ()
{
CFAA aa;
CFBB bb;
boost::function<void()> func1;
func1 = boost::bind(&CFAA::methodAA, &aa);
func1();
func1 = boost::bind(&CFBB::methodB, &bb);
func1();
func1 = boost::bind(&CFAA::methodArgInt, &aa, 11); // 虽然是boost::function<void()> 类型,但还是可以在后面加参数(可用度很高)
func1();
bb.methodArgBind(func1, 22);
boost::function<void(int)> func2;
func2 = boost::bind(&CFAA::methodArgInt, &aa, _1);
bb.methodArgBind(func2);
return 0;
}
boost::function boost::bind 简单示例
最新推荐文章于 2023-08-24 06:35:30 发布