将循环转移到C++03 for each

transfer loop into C++03 for_each

本文关键字:for each C++03 循环 转移      更新时间:2023-10-16

可能重复:
对通过引用获取参数的方法使用bind1st

我有以下传统的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中使用lambda,但这不是重点。)不幸的是,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的一部分。有什么变通办法吗?

为什么不简单地使用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));
}