您的位置:首页 > 其它

<转载>Boost.Bind的基础使用

2010-12-30 09:49 351 查看
原文http://www.cppblog.com/walkspeed/archive/2007/07/20/28448.html 当我们使用函数时习惯于C函数的格式,即如下形式
resulttype funname( arglist );
返回值类型 函数名( 参数列表 );

在Boost.Function中,我们可以方便的定义定义函数对象。不过在定义用来表示类成员函数的函数对象时
第一个参数是类指针。而且在调用时,要传入一个类实例的指针。这样用起来并不是很方便,因为调用者
要知道类实例。这实际上没有实现解耦。而解耦是我们使用回调或委托设计的一个目标。

为了解决这个问题,我们要使用Boost.Bind库

Boost.Bind是一个函数对象工厂。他用来产生我们需要的函数对象。好了,有了它,你可以在你设计中大
量使用Boost.Function。不用再去定义类成员函数形式的函数对象啦,只用定义普通函数对象。

一个简单的例子

class CExample
{
public:
bool printstr( const std::string &str )
{
std::cout << "CExample::printstr" << str << std::endl;
return true;
}
};

//定义一个函数对象
boost::function< bool ( const std::string& ) > printstr;

//用Boost.Bind创建一个函数对象,赋给printstr
CExample example;
printstr = boost::bind( &CExample::printstr, &example, _1 );

好了,我们创建了一个函数对象,而且调用时不再需要类实例拉。用Boost.Function和Boost.Bind大大
的简化了Command模式的实现。

在上面的例子中要个古怪的对象"_1"。这个叫做站位符,他代表这个位置有个参数,但现在还不知道参
数是什么。_1代表参数列表中的第一个位置上的参数。Boost.Bind一共定义了9个站位符对象。如下
_1,_2,_3,_4,_5,_6,_7,_8,_9。分别代表参数列表中位子。

Boost.Bind产生的函数对象可以直接使用,利用上面的例子。

bool b = boost::bind( &CExample::printstr, &example, _1 )( "Hello World" );

posted on 2007-07-20 17:15 walkspeed 阅读(3477) 评论(2) 编辑 收藏 引用 所属分类: STL、Boost、范型编程C++语言



FeedBack:# re: Boost.Bind的基础使用2007-07-30 13:07 | 金庆
[align=left]没有显示出boost::bind有什么优越性。如
bool b = example.printstr( "Hello World" );
为什么要写成这样:
bool b = boost::bind( &CExample::printstr, &example, _1 )( "Hello World" );

回复 更多评论
[/align]# re: Boost.Bind的基础使用2008-01-16 18:51 | uzstudio
[align=left]不错,简化了Command模式的实现 回复 更多评论
[/align]# re: Boost.Bind的基础使用2010-12-30 09:45 | goldenlock
[align=left]@金庆
vector<string> vec;
vec.push_back("abc");
vec.push_back("def");
std::for_each(vec.begin(),vec.end(), printstr) 回复 更多评论
[/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: