using boost.lambda in std::for
I'm currently learning new features in C++11 and boost, such as lambda and boost::function.
I'm trying to use boost.lambda in std::for_each, with the iterated type being boost::function.
The code looks like this:
void task1(int a)
{
std::cout << "task1: " << a << std::endl;
}
void task2(const std::string& str)
{
std::cout << "task2: " << str << std::endl;
}
int main()
{
std::list<boost::function<void()> > functions;
functions.push_back(boost::bind(&task1, 5));
functions.push_back(boost::bind(&task2, "test string"));
// working
std::list<boost::function<void()> >::iterator i = functions.begin();
for (; i != functions.end(); ++i)
{
(*i)();
}
// also working
std::for_each(functions.begin(), functions.end(), [](boost::function<void()>& f){f();});
// trying to use boost::lambda but none compiles.
std::for_each(functions.begin(), functions.end(), boost::lambda::bind(_1));
std::for_each(
functions.begin(),
functions.end(),
boost::lambda::bind(&boost::function<void()>::operator(), &_1, _1));
std::for_each(
functions.begin(),
functions.end(),
boost::lambda::bind(std::mem_fn(&boost::function<void()>::operator(), _1));
return 0;
}
How can call a boost::function object with boost::lambda? I think I'm supposed to wrap it with boost::lambda::bind(), but I just don't know how. I have read the boost.lambda document, but I didn't find anything useful there.
为了使这个工作,你必须显式限定boost::lambda
以便你的意思是boost::lambda::_1
而不是boost/bind
boost::arg
来自boost/bind
。
std::for_each(functions.begin(), functions.end(),
boost::lambda::bind(boost::lambda::_1));
链接地址: http://www.djcxy.com/p/47360.html
上一篇: 返回迭代器来提升适配器