可能重复:
Using bind1st for a method that takes argument by reference传递回路成C++ 03的for_each
我有以下传统的C++ 03循环(使用auto
仅堆栈溢出空间效率):
for (auto it = some_vector.begin(); it != some_vector.end(); ++it)
{
foobar.method(*it);
}
在C++ 11中,我设法将其重写为以下内容for_each
调用它工作得很好:
std::for_each(some_vector.begin(), some_vector.end(),
std::bind(&Foobar::method, std::ref(foobar), _1));
(当然,我可以只使用C++ 11的λ,但是这不是重点)不幸的是,std::bind
不是C++ 03的一部分,所以我试着用std::bind1st
和std::mem_fun_ref
模拟它:
std::for_each(some_vector.begin(), some_vector.end(),
std::bind1st(std::mem_fun_ref(&Foobar::method), std::ref(foobar)));
但是,这引发了Visual Studio中的C2535错误( “成员函数已经定义或声明”):
// inside class binder1st in header xfunctional
result_type operator()(const argument_type& _Right) const
{ // apply functor to operands
return (op(value, _Right));
}
result_type operator()(argument_type& _Right) const
{ // apply functor to operands <--- ERROR C2535 HERE
return (op(value, _Right));
}
这是Visual Studio中的常量正确性错误,还是我做错了什么?
此外,std::ref
似乎不是C++ 03的一部分。有什么解决方法吗?
即使你不能逃脱我的编辑锤! – 2012-01-10 17:41:44
'std :: tr1 :: bind'是TR1的一部分 - 是否足够满足您的需求? – ildjarn 2012-01-10 17:42:50
可能会感兴趣:[是否可以创建函数本地闭包pre-C++ 11?](http://stackoverflow.com/questions/5723619/is-it-possible-to-create-function-local -closures预-C11)。 – Xeo 2012-01-10 17:44:21