C++学习 boost学习之-function

来源:互联网 发布:vue.js createelement 编辑:程序博客网 时间:2024/05/21 21:33

要点:

1 用于保存函数对象,本身是函数对象

2 与bind一起使用,威力巨大:

class command {  boost::function<void()> f_;public:  command() {}  command(boost::function<void()> f):f_(f) {}  void execute() {    if (f_) {      f_();    }  }  template <typename Func> void set_function(Func f) {    f_=f;  }  bool enabled() const {    return f_;  }};

int main() {  tape_recorder tr;  command play(boost::bind(&tape_recorder::play,&tr));  command stop(boost::bind(&tape_recorder::stop,&tr));  command forward(boost::bind(&tape_recorder::stop,&tr));  command rewind(boost::bind(&tape_recorder::rewind,&tr));  command record;  // 从某些GUI控制中调用...  if (play.enabled()) {    play.execute();  }  // 从某些脚本客户端调用...  stop.execute();  // Some inspired songwriter has passed some lyrics  std::string s="What a beautiful morning...";  record.set_function(    boost::bind(&tape_recorder::record,&tr,s));  record.execute();}

3 Boost.Function 也可与Boost.Lambda一起使用


总结,function与bind一起使用的作用之大用语言已无法说完全说明!禅/道在心中!

0 0