-
/*
-
* function.cpp
-
*
-
* Created on: 2013-7-22
-
* Author: root
-
*/
-
/*
-
#include <iostream>
-
#include "boost/function.hpp"
-
-
bool some_func(int i,double d)
-
{
-
return i > d;
-
}
-
-
int main()
-
{
-
boost::function<bool (int,double)>f;
-
f = &some_func;
-
-
f(10,1.1);
-
}
-
*/
-
-
#include <iostream>
-
#include <vector>
-
#include <algorithm>
-
#include "boost/function.hpp"
-
-
void print_new_value(int i) {
-
std::cout << "The value has been updated and is now " << i << '\n';
-
}
-
-
void interested_in_the_change(int i) {
-
std::cout << "Ah,the value has changed."<< i << "\n";
-
}
-
-
//class notifier {
-
// typedef void (*function_type)(int);
-
// std::vector<function_type> vec_;
-
// int value_;
-
//public:
-
// void add_observer(function_type t) {
-
// vec_.push_back(t);
-
// }
-
//
-
// void change_value(int i){
-
// value_ = i;
-
// for(std::size_t i=0; i<vec_.size(); ++i) {
-
// (*vec_[i])(value_);
-
// }
-
// }
-
//};
-
//改进后的类,支持对象,指针,boost::function实例
-
class notifier {
-
typedef boost::function<void (int)>function_type;
-
std::vector<function_type> vec_;
-
int value_;
-
public:
-
template <typename T> void add_observer(T t) {
-
vec_.push_back(function_type(t));
-
}
-
-
void change_value(int i){
-
value_ = i;
-
for(std::size_t i=0; i<vec_.size(); ++i) {
-
vec_[i](value_);
-
}
-
}
-
};
-
-
class knows_the_previous_value{
-
int last_value_;
-
public:
-
void operator()(int i) {
-
static bool first_time = true;
-
if(first_time) {
-
last_value_ = i;
-
std::cout << "This is the first change of value, \
-
so I don't know the previous one.\n";
-
first_time = false;
-
return;
-
}
-
std::cout << "Previous value was " << last_value_ << '\n';
-
last_value_ = i;
-
}
-
};
-
/*
-
int main() {
-
notifier n;
-
n.add_observer(&print_new_value);
-
n.add_observer(&interested_in_the_change);
-
n.add_observer(knows_the_previous_value()); //使用带状态(参数)的对象是这个功能的亮点
-
-
n.change_value(42);
-
std::cout << "\n";
-
n.change_value(30);
-
}
-
*/
阅读(1530) | 评论(0) | 转发(0) |