怎样使用boost:bind?该如何处理
怎样使用boost::bind?
学习使用Boost::bind,但老是不对,在此提出问题,望高手不吝指导:
class status
{
std::string name_;
bool ok_;
public:
explicit status(const std::string& name) : name_(name), ok_(true) {}
void break_it()
{
ok_ = false;
}
bool is_broken()const
{
return ok_;
}
void report()const
{
std::cout << name_ << " is " << (ok_ ? "working normally":"terribly broken") << std::endl;
}
const std::string& getname()const
{
return name_;
}
};
void report( const std::string surname, const boost::shared_ptr<status>& s )
{
std::cout << surname << " " << s->getname() << " is " << (s->is_broken() ? "working normally":"terribly broken") << std::endl;
}
void foo()
{
std::vector<boost::shared_ptr<status> > stautues;
stautues.push_back(boost::shared_ptr<status>(new status("status 1")));
stautues.push_back(boost::shared_ptr<status>(new status("status 2")));
//以下两个式子都不对,第一个说“zhang"不是一个占位符,第二个不知道原因,
//需要知道怎样才能将report函数bind至for_each;
std::for_each(stautues.begin(), stautues.end(),
(boost::bind<void>(&report, "zhang", _2 ))); //Error C2118 negative subscription;
std::for_each(stautues.begin(), stautues.end(),
(boost::bind<void>(&report, _1, _2 ))("zhang")); //error C2784:
//could not deduce template argument for
//'_Fn1' from 'void'
}
------解决方案--------------------
试试
boost::bind<void>(&report, std::string("zhang"), _2)
另外最好使用VC 7.1(2003)以上版本或者gcc 3以上的版本
学习使用Boost::bind,但老是不对,在此提出问题,望高手不吝指导:
class status
{
std::string name_;
bool ok_;
public:
explicit status(const std::string& name) : name_(name), ok_(true) {}
void break_it()
{
ok_ = false;
}
bool is_broken()const
{
return ok_;
}
void report()const
{
std::cout << name_ << " is " << (ok_ ? "working normally":"terribly broken") << std::endl;
}
const std::string& getname()const
{
return name_;
}
};
void report( const std::string surname, const boost::shared_ptr<status>& s )
{
std::cout << surname << " " << s->getname() << " is " << (s->is_broken() ? "working normally":"terribly broken") << std::endl;
}
void foo()
{
std::vector<boost::shared_ptr<status> > stautues;
stautues.push_back(boost::shared_ptr<status>(new status("status 1")));
stautues.push_back(boost::shared_ptr<status>(new status("status 2")));
//以下两个式子都不对,第一个说“zhang"不是一个占位符,第二个不知道原因,
//需要知道怎样才能将report函数bind至for_each;
std::for_each(stautues.begin(), stautues.end(),
(boost::bind<void>(&report, "zhang", _2 ))); //Error C2118 negative subscription;
std::for_each(stautues.begin(), stautues.end(),
(boost::bind<void>(&report, _1, _2 ))("zhang")); //error C2784:
//could not deduce template argument for
//'_Fn1' from 'void'
}
------解决方案--------------------
试试
boost::bind<void>(&report, std::string("zhang"), _2)
另外最好使用VC 7.1(2003)以上版本或者gcc 3以上的版本