2012-01-10 57 views
3

可能重复:
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::bind1ststd::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的一部分。有什么解决方法吗?

+0

即使你不能逃脱我的编辑锤! – 2012-01-10 17:41:44

+3

'std :: tr1 :: bind'是TR1的一部分 - 是否足够满足您的需求? – ildjarn 2012-01-10 17:42:50

+0

可能会感兴趣:[是否可以创建函数本地闭包pre-C++ 11?](http://stackoverflow.com/questions/5723619/is-it-possible-to-create-function-local -closures预-C11)。 – Xeo 2012-01-10 17:44:21

回答

3

为什么不简单地使用std::mem_fun?它期望一个指针作为第一个参数,因此:

#include <functional> 
#include <algorithm> 
#include <vector> 

struct foo{ 
    void method(int){} 
}; 

int main(){ 
    std::vector<int> v; 
    foo f; 
    std::for_each(v.begin(), v.end(), 
     std::bind1st(std::mem_fun(&foo::method), &f)); 
} 
+0

+1我证明了它http://ideone.com/AAR4S – 2012-01-11 16:14:54