繁体   English   中英

C ++:难以部分应用

[英]C++: Difficulty with partial application

我正在尝试使用函数参数的部分应用程序,以便可以使用STL的find_if 这是一个示例程序:(为简洁起见,合并了类头和实现。)

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

using namespace std;

struct Odp
{
    int id;

    Odp(int id)
    {
        this->id = id;
    }

    ~Odp()
    {
        cout << "Destructing Odp " << id << endl;
    }
};

typedef vector<Odp*> OdpVec;

class Foo
{
public:
    void loadUp()
    {
        vec.push_back(new Odp(0));
        vec.push_back(new Odp(1));
        vec.push_back(new Odp(2));
    }
    void printWithID(int id)
    {
        OdpVec::iterator iter = find_if(vec.begin(), vec.end(), bind1st(&hasID, id));
        if (iter != vec.end())
        {
            cout << "Odp at " << *iter << " has id " << id << endl;
            return;
        }
        cout << "No Odp with id " << id << " could be found." << endl; 
    }

private:
    OdpVec vec;
    bool hasID(int id, Odp* odp)
    {
        return odp->id == id;
    }
};

int main()
{
    Foo foo;
    foo.loadUp();
    foo.printWithID(1);
}

但是,这甚至无法编译。 错误是:

error C2276: '&' : illegal operation on bound member function expression

我在这里做错了什么?

UPDATE使hasID()为自由浮动函数会导致以下错误:

error C2664: 'std::find_if' : cannot convert parameter 3 from 'std::binder1st<_Fn2>' to 'std::binder1st<_Fn2>'
1>          with
1>          [
1>              _Fn2=bool (__cdecl *)(int,Odp &)
1>          ]
1>          Cannot copy construct class 'std::binder1st<_Fn2>' due to ambiguous copy constructors or no available copy constructor
1>          with
1>          [
1>              _Fn2=bool (__cdecl *)(int,Odp &)
1>          ]

bind_1st应该与不是成员函数的functors一起使用。

Functor是带有重载operator()的对象。

您可以使用mem_fn围绕您的成员函数构造一个适配器。

在您的情况下,由于hasID不使用this ,因此仅使用静态方法就可以完成。 (然后,您不必this绑定为第一个参数)

您必须使hasID成为static函数(或完全从Foo中提取它)。 您希望在活页夹中有一个普通的函数指针,而没有指向成员函数的指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM