点击(此处)折叠或打开
-
/*
-
* function2.cpp
-
*
-
* Created on: 2013-7-24
-
* Author: root
-
*/
-
-
#include <iostream>
-
#include "boost/function.hpp"
-
#include "boost/bind.hpp"
-
/*
-
//带状态的类对象
-
class keeping_state {
-
int total_;
-
public:
-
keeping_state():total_(0){}
-
-
int operator()(int i) { //括号重载 void operator()()
-
total_+= i;
-
return total_;
-
}
-
-
int total() const {
-
return total_;
-
}
-
};
-
-
int main() {
-
keeping_state ks;
-
// boost::function<int(int)> f1;
-
//// f1 = ks; 使用拷贝对象时并不能同时改变total_
-
// f1 = boost::ref(ks);//使用引用, 常量引用boost::cref
-
//
-
// boost::function<int(int)> f2;
-
// f2 = boost::ref(ks);
-
-
//第二种示例
-
boost::function1<int,int> f1;
-
// f1 = ks;使用拷贝对象时并不能同时改变total_
-
f1 = boost::ref(ks);
-
-
boost::function1<int,int> f2(f1);
-
boost::function1<short,short> f3(f2);
-
-
-
std::cout << "The current f1 total is " << f1(10) << '\n';
-
std::cout << "The current f2 total is " << f2(10) << '\n';
-
std::cout << "The current f2 total is " << f3(10) << '\n';
-
std::cout << "After adding 10 two times,the total is " << ks.total() << '\n';
-
}
-
*/
-
-
-
//boost.function 与 boost.bind 合用,让调用代码对被调用代码无所知,实现解耦
-
class tape_recorder {
-
public:
-
void play() {
-
std::cout << "Since my baby left me ...\n";
-
}
-
-
void stop() {
-
std::cout << "OK, taking a break \n";
-
}
-
-
void forward() {
-
std::cout << "whizzz\n";
-
}
-
-
void rewind() {
-
std::cout << "zzzihw\n";
-
}
-
-
void record(const std::string& sound) {
-
std::cout << "Recorder: "<< sound << " \n";
-
}
-
};
-
-
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::forward,&tr));
-
command rewind(boost::bind(&tape_recorder::rewind,&tr));
-
command record;
-
-
//boost::function<void()> f(boost::bind(&tape_recorder::play,&tr));
-
//f = boost::ref(play);
-
if(play.enabled()){
-
play.execute();
-
}
-
-
//pass some lyrics
-
std::string s="What a beautiful morning...";
-
record.set_function(
-
boost::bind(&tape_recorder::record,&tr,s));
-
record.execute();
-
- }