for_each中的类方法

class method in for_each

本文关键字:类方法 each for      更新时间:2023-10-16

有一个类和事件结构:

struct Foo
{
    Foo(): name("nx"), val(9) {}
    string name;
    int val;
};
class Base
{
    public:
        Base()
        {
            /*array.push_back(Foo());
            array.push_back(Foo());
            array.push_back(Foo());             //fill array Foo
            array.push_back(Foo());
            array.push_back(Foo());*/
        }
        void Define(Foo* desktop)
        {
            cout << desktop->name << " " << desktop->val << "n";
        }
        void Oblem()
        {
            /*for(int i = 0; i < array.size(); ++i)
            {
                Define(&array[i]);
            }*/
            for_each(array.begin(), array.end(), mem_fun_ref(&Base::Define));
        }
    public:
        std::vector<Foo> array;
};

如何替换算法for_each上注释掉的循环?

我现在有这些错误:

  1. 错误:没有匹配调用'(std::mem_fun1_ref_t) (Foo&)'|
  2. 候选者有:_Ret std::mem_fun1_ref_t<_Ret, _Tp, _Arg>::operator()(_Tp&, _Arg) const [with _Ret = void, _Tp = Base, _Arg = Foo*]|

Base::Define有两个参数:Foo* desktop和一个隐式的Base* this。您需要在Oblem中绑定当前的this,以获得仅接受Foo的函数。此外,Define应该将其参数作为Foo& desktop(或者更好,如果是真实代码,则为Foo const& desktop)。

使用TR1内的标准功能(或其Boost实现)的完整解决方案将是:

void Define(Foo const& desktop) const
{
    cout << desktop.name << " " << desktop.val << "n";
}
void Oblem() const
{
    for_each(
        array.begin(), array.end()
      , std::bind( &Base::Define, this, _1 )
    );
}
class Base
{
public:
    Base() : array(5) {}

    void Define(Foo &desktop)
    {
        cout << desktop.name << " " << desktop.val << "n";
    }
    void Oblem()
    {
        for_each(array.begin(),array.end(),[this](Foo &f) {
            Define(f);
        });
        // or
        for_each(array.begin(),array.end(),
          bind(&Base::Define,this,placeholders::_1));
    }
public:
    std::vector<Foo> array;
};