要点:
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一起使用的作用之大用语言已无法说完全说明!禅/道在心中!
本文深入探讨了Boost.Function与bind在C++编程中的应用,展示了它们如何协同工作,提供灵活且强大的函数对象操作能力。通过具体实例,如在控制台应用程序中实现播放、停止、录制等功能,阐述了它们在简化代码、提高复用性和减少耦合方面的优势。
2780

被折叠的 条评论
为什么被折叠?



