您的位置:首页 > 其它

boost function bind用法

2012-08-19 20:57 288 查看
#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace boost;

void ShowValue(const std::string &value)
{
std::cout << "this is value:" << value << std::endl;
}

class Demo
{
public:
// 声明一个返回值未void,参数为const std::string&的函数对象
typedef function<void (const std::string&)> Callback;

void Show(std::string &name, std::string &value)
{
std::cout << "this is name:" << name << std::endl;
_callback(value);
}

// const必须,原因不明
void SetValue(const Callback &cb)
{
_callback = cb;
}

private:
Callback _callback;
};

int main(void)
{
Demo d;
Demo *pd = &d;
Demo &rd = d;
std::string name("tjw");
std::string value("0714");

// 绑定一个普通函数并执行,_1占位符,如果不带后面的(value)是不会执行的
bind(ShowValue, _1)(value);

//d.SetValue(ShowValue);
// 绑定普通函数
d.SetValue(bind(ShowValue, _1));

// 绑定成员函数并执行,需要传入成员函数的地址和调用这个成员函数的对象或指向对象的指针
bind(&Demo::Show, pd, _1, _2)(name, value);
system("pause");
}
// Widget类与WidgetImpl类之间是组合的关系, 我们把实现放到WidgetImpl中去做。
// Widget提供外部接口,供用户去扩展(继承自Widget,如Wrap),或者将Widget::test设置为纯虚函数

#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/function.hpp>

class WidgetImpl
{
public:
void setTest(boost::function<void()> test)
{
test_ = test;
}

void onTest()
{
test_();
}

private:
boost::function<void()> test_;
};

class Widget
{
public:
Widget()
{
impl_.setTest(boost::bind(&Widget::test, this));
}

void myTest()
{
impl_.onTest();
}

virtual void test();
{
std::cout << "widget test" << std::endl;
}

private:
WidgetImpl impl_;
};

class Wrap : public Widget
{
public:
void test()
{
std::cout << "wrap test" << std::endl;
}
};

int main()
{
Widget *p = new Wrap();
p->myTest();

system("pause");
}


#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/function.hpp>
#include <string>

class Timer
{
public:
Timer(boost::asio::io_service& io, long seconds)
: seconds_(seconds), timer_(io, boost::posix_time::seconds(seconds))
{
}

void setTimer(boost::function<void(std::string)> func)
{
onTimer_ = func;
timer_.async_wait(boost::bind(&Timer::handleWait, this));
}

private:
void handleWait()
{
onTimer_("");
timer_.expires_from_now(boost::posix_time::seconds(seconds_));
timer_.async_wait(boost::bind(&Timer::handleWait, this));
}

private:
long seconds_;
boost::asio::deadline_timer timer_;
boost::function<void(std::string)> onTimer_;
};

void onTimer(std::string str)
{
std::cout << str << std::endl;
}

int main()
{
boost::asio::io_service io;
Timer timer(io, 1);
timer.setTimer(boost::bind(onTimer, "xyz"));
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
t.join();

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: