1. 程式人生 > >C++學習 boost學習之-function

C++學習 boost學習之-function

要點:

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一起使用的作用之大用語言已無法說完全說明!禪/道在心中!